﻿using AutoMapper;
using DFGK.IRepository;
using DFGK.IService;
using DFGK_WMS.Common;
using DFGK_WMS.Context;
using DFGK_WMS.Model.Dto;
using DFGK_WMS.Model.Dto.YS;
using DFGK_WMS.Model.Enum;
using DFGK_WMS.Model.Models;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Hosting;
using Microsoft.IdentityModel.Tokens;
using Newtonsoft.Json;
using NPOI.SS.Formula.Functions;
using NPOI.SS.UserModel;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection.Emit;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Yitter.IdGenerator;

namespace DFGK.Service
{
    public class ShippingOrderDetailService : BaseService, IShippingOrderDetailService
    {
        private readonly IShippingReplenishmentRepository _shippingReplenishmentRepository;
        private readonly IReceivingOrderDetailRepository _receivingOrderDetailRepository;
        private readonly IReceivingBillDetailRepository _receivingBillDetailRepository;
        private readonly IReceivingBillRepository _receivingBillRepository;
        private readonly IShippingOrderDetailRepository _shippingOrderDetailRepository;
        private readonly IShippingLockCellRepository _shippingLockCellRepository;
        private readonly IPickingOrderDetailRepository _pickingOrderDetailRepository;
        private readonly IPutawayOrderDetailRepository _putawayOrderDetailRepository;
        private readonly IMaterialPackageRepository _materialPackageRepository;
        private readonly IMaterialRepository _materialRepository;
        private readonly IStockRepository stockRepository;
        private readonly IOtherTypeRepository _otherTypeRepository;
        private readonly HttpClientHelper _httpClientHelper;
        private readonly IInventoryDetailRepository _inventoryDetailRepository;
        private readonly IPackageDetailRepository _packageDetailRepository;
        private readonly IInterfaceLogRepository _interfaceLogRepository;
        private readonly IShippingLockCellRepository _lockCellRepository;
        private readonly IPutawayOrderRepository _putawayOrderRepository;
        private readonly IPickingOrderRepository _pickingOrderRepository;
        private readonly IInventoryLogRepository _inventoryLogRepository;
        private readonly ICachePortRepository _cachePortRepository;
        private readonly IWarehouseRepository _warehouseRepository;
        private readonly IInventoryRepository _inventoryRepository;
        private readonly IDepartMentRepository _departMentRepository;
        private readonly IRoutewayRepository _routewayRepository;
        private readonly ISupplierRepository _supplierRepository;
        private readonly ICustomerRepository _customerRepository;
        private readonly IInstructRepository _instructRepository;
        private readonly IPalletRepository _palletRepository;
        private readonly IShelfRepository _shelfRepository;
        private readonly IAreaRepository _areaRepository;
        private readonly IPackRepository _packRepository;
        private readonly ICellRepository _cellRepository;
        private readonly WcsHttpClient _wcsHttpClient;
        private readonly IUnitOfWork _unitOfWork;

        public ShippingOrderDetailService(IMapper mapper, IShippingOrderDetailRepository _shippingOrderDetailRepository, IInventoryRepository inventoryRepository, IShippingLockCellRepository lockCellRepository, ISupplierRepository _supplierRepository, ICustomerRepository _customerRepository, IWarehouseRepository _warehouseRepository, IAreaRepository _areaRepository, IMaterialPackageRepository _materialPackageRepository, IUnitOfWork unitOfWork, ICellRepository cellRepository, IInstructRepository _instructRepository, IPickingOrderRepository _pickingOrderRepository, IPickingOrderDetailRepository _pickingOrderDetailRepository, IPalletRepository _palletRepository, IInventoryLogRepository _inventoryLogRepository, IInventoryDetailRepository inventoryDetailRepository, IPutawayOrderRepository putawayOrderRepository, IPutawayOrderDetailRepository _putawayOrderDetailRepository, ICachePortRepository _cachePortRepository, IPackRepository _packRepository, IPackageDetailRepository _packageDetailRepository, IReceivingOrderDetailRepository _receivingOrderDetailRepository, IRoutewayRepository _routewayRepository, IShelfRepository _shelfRepository, IShippingReplenishmentRepository _shippingReplenishmentRepository, IInterfaceLogRepository _interfaceLogRepository, WcsHttpClient _wcsHttpClient, IMaterialRepository materialRepository, IDepartMentRepository departMentRepository, IReceivingBillDetailRepository receivingBillDetailRepository, IReceivingBillRepository receivingBillRepository, IStockRepository stockRepository, IOtherTypeRepository otherTypeRepository, HttpClientHelper httpClientHelper, IShippingLockCellRepository shippingLockCellRepository) : base(mapper)
        {
            this._shippingReplenishmentRepository = _shippingReplenishmentRepository;
            this._receivingOrderDetailRepository = _receivingOrderDetailRepository;
            this._shippingOrderDetailRepository = _shippingOrderDetailRepository;
            this._pickingOrderDetailRepository = _pickingOrderDetailRepository;
            this._putawayOrderDetailRepository = _putawayOrderDetailRepository;
            this._materialPackageRepository = _materialPackageRepository;
            this._packageDetailRepository = _packageDetailRepository;
            this._pickingOrderRepository = _pickingOrderRepository;
            this._inventoryLogRepository = _inventoryLogRepository;
            this._interfaceLogRepository = _interfaceLogRepository;
            this._warehouseRepository = _warehouseRepository;
            this._cachePortRepository = _cachePortRepository;
            this._routewayRepository = _routewayRepository;
            this._supplierRepository = _supplierRepository;
            this._customerRepository = _customerRepository;
            this._instructRepository = _instructRepository;
            this._palletRepository = _palletRepository;
            this._shelfRepository = _shelfRepository;
            this._areaRepository = _areaRepository;
            this._packRepository = _packRepository;
            this._wcsHttpClient = _wcsHttpClient;
            _materialRepository = materialRepository;
            _inventoryDetailRepository = inventoryDetailRepository;
            _putawayOrderRepository = putawayOrderRepository;
            _inventoryRepository = inventoryRepository;
            _lockCellRepository = lockCellRepository;
            _cellRepository = cellRepository;
            _unitOfWork = unitOfWork;
            _departMentRepository = departMentRepository;
            _receivingBillDetailRepository = receivingBillDetailRepository;
            _receivingBillRepository = receivingBillRepository;
            this.stockRepository = stockRepository;
            _otherTypeRepository = otherTypeRepository;
            _httpClientHelper = httpClientHelper;
            _shippingLockCellRepository = shippingLockCellRepository;
        }
        #region PC
        public bool AddShippingOrderDetail(ShippingOrderDetail m, out string message)
        {
            bool result = false;
            bool ispick = m.BillType == 1 ? false : true;
            message = string.Empty;
            if (m.SupplierId != null)
            {
                var sobj = _supplierRepository.QueryEntityById((long)m.SupplierId);
                if (sobj != null)
                {
                    m.SupplierName = sobj.Name;
                }
                else
                {
                    message = "供应商不存在或者已被禁用！";
                    return false;
                }
            }
            if (m.CustomerId != null)
            {
                var cobj = _customerRepository.QueryEntityById((long)m.CustomerId);
                if (cobj != null)
                {
                    m.CustomerName = cobj.Name;
                }
                else
                {
                    message = "客户不存在或者已被禁用！";
                    return false;
                }
            }
            if (!string.IsNullOrEmpty(m.AreaCode))
            {
                var aobj = _areaRepository.QueryEntityWhere(x => x.Code == m.AreaCode);
                if (aobj == null || aobj.Status != 1)
                {
                    message = "库区不存在或者已被禁用！";
                    return false;
                }
            }
            m.Status = 0;
            m.ShippedQty = 0;
            m.SourceType = 0;
            //是否挂起-逻辑待处理
            m.IsSuspend = false;
            try
            {
                var materialpacklist = _materialPackageRepository.GetEntityAlls();
                _unitOfWork.BeginTransaction();
                foreach (var item in m.LockCellList)
                {
                    _shippingOrderDetailRepository.AddEntity(m);
                    _unitOfWork.SaveChangesEntity();
                    if (item.InventoryId == null)
                    {
                        message = "找不到库存信息！";
                        _unitOfWork.RollbackChanges();
                        return false;
                    }
                    var invobj = _inventoryRepository.QueryEntityById((long)item.InventoryId);
                    if (invobj == null)
                    {
                        message = "库存信息有误！";
                        _unitOfWork.RollbackChanges();
                        return false;
                    }
                    m.AreaCode = invobj.AreaCode;
                    m.AreaName = invobj.AreaName;
                    m.WarehouseId = invobj.WarehouseId;
                    m.WarehouseCode = invobj.WarehouseCode;
                    m.WarehouseName = invobj.WarehouseName;
                    m.MaterialId = invobj.MaterialId == null ? 0 : Convert.ToInt64(invobj.MaterialId);
                    m.MaterialName = invobj.MaterialName;
                    m.MaterialCode = invobj.MaterialCode;
                    m.MaterialTypeCode = invobj.MaterialTypeCode;
                    m.UnitId = invobj.UnitId;
                    m.UnitName = invobj.UnitName;
                    m.BatchNo = invobj.BatchNo;
                    
                    
                        if (item.OutQty > item.InventoryQty)
                        {
                            message = $"物资{invobj.MaterialCode}出库数量不能大于库存数量！";
                            _unitOfWork.RollbackChanges();
                            return false;
                        }
                        else
                            m.Qty = item.OutQty;
                        invobj.PickedQty += item.OutQty;
                        invobj.AllocateQty += item.OutQty;
                        invobj.IsLock = true;
                    
                    _shippingOrderDetailRepository.UpdEntity(m);
                    item.OrderDetailId = m.Id;
                    item.OrdeSn = m.OrderSn;
                    item.CellId = invobj.LocationId;
                    item.CellCode = invobj.LocationCode;
                    item.CellName = invobj.LocationName;
                    item.CellDepthIndex = invobj.LocationDepth;
                    item.WhId = invobj.WarehouseId;
                    item.PalletBarcode = invobj.PalletBarcode;
                    item.MaterialId = invobj.MaterialId;
                    item.MaterialCode = invobj.MaterialCode;
                    item.MaterialName = invobj.MaterialName;
                    item.MaterialKeyId = invobj.MaterialKeyId;
                    item.RoutewayId = invobj.RoutewayId;
                    item.BatchNo = invobj.BatchNo;
                    item.InventoryQty = invobj.AvailableQty;
                    if (item.OutQty <= 0)
                    {
                        message = "出库数量不能为0！";
                        _unitOfWork.RollbackChanges();
                        return false;
                    }
                    if (item.OutQty % 1 != 0)
                    {
                        message = "出库数量不能是小数";
                        _unitOfWork.RollbackChanges();
                        return false;
                    }
                    if (!ispick)
                    {
                        if (m.Qty == invobj.AvailableQty)
                            m.BillType = 1;
                        else
                            m.BillType = 2;
                    }
                    _lockCellRepository.AddEntity(item);
                    result = _unitOfWork.SaveChangesEntity();
                    if (result == false)
                        break;
                }
                if (result)
                {
                    _unitOfWork.CommitChanges();
                    return true;
                }
                _unitOfWork.RollbackChanges();
                return false;
            }
            catch (Exception)
            {
                _unitOfWork.RollbackChanges();
                throw;
            }

        }

        public bool DelShippingOrderDetail(long id, out string message)
        {
            message = string.Empty;
            var sobj = _shippingOrderDetailRepository.QueryEntityById(id);
            if (sobj != null)
            {
                if (sobj.Status == 3 || sobj.Status == 4)
                {
                    message = "作业中和已完成的单据不可删除！";
                    return false;
                }
                _shippingOrderDetailRepository.DelEntity(sobj);
                var slobj = _lockCellRepository.QueryEntityWhere(x => x.OrderDetailId == sobj.Id);
                if (slobj != null)
                {
                    if (slobj.InventoryId == null)
                    {
                        message = "库存信息有误！";
                        return false;
                    }
                    _lockCellRepository.DelEntity(slobj);
                    var iobj = _inventoryRepository.QueryEntityById((long)slobj.InventoryId);
                    if (iobj != null)
                    {
                        iobj.IsLock = false;
                        iobj.PickedQty -= slobj.OutQty;
                        iobj.AllocateQty -= slobj.OutQty;
                        iobj.Status = 1;
                        iobj.Remark = string.Empty;
                        _inventoryRepository.UpdEntity(iobj);
                    }
                    var srobj = _shippingReplenishmentRepository.QueryEntityWhere(x => x.OrderId == sobj.Id);
                    if (srobj != null)
                    {
                        _shippingReplenishmentRepository.DelEntity(srobj);
                        if (srobj.FromInventoryId == null)
                        {
                            message = "库存信息有误！";
                            return false;
                        }
                        var frominobj = _inventoryRepository.QueryEntityById((long)srobj.FromInventoryId);
                        if (frominobj != null)
                        {
                            frominobj.IsLock = false;
                            frominobj.PickedQty -= sobj.Qty - slobj.InventoryQty;
                            frominobj.AllocateQty = 0;
                            frominobj.Status = 1;
                            frominobj.Remark = string.Empty;
                            _inventoryRepository.UpdEntity(frominobj);
                        }
                    }
                }
                return _unitOfWork.SaveChangesEntity();
            }
            message = "找不到出库单！";
            return false;
        }

        public List<ShippingSelectMaterialDto> GetInventoryByMaterialAll(int pageIndex, int pageSize, string? mname, string? arecode, string? SuplierName, string? StockName, out int count)
        {
            var ilist = _inventoryRepository.GetEntityAlls();
            ilist = ilist.Where(x => x.Status == 1 && x.IsLock == false);

            if (!string.IsNullOrEmpty(arecode))
                ilist = ilist.Where(i => i.AreaCode == arecode);
            if (!string.IsNullOrEmpty(mname))
            {
                ilist = ilist.Where(i => i.MaterialName.Contains(mname) || i.MaterialCode.Contains(mname));
            }
            if (!string.IsNullOrEmpty(SuplierName))
            {
                ilist = ilist.Where(i => i.SupplierName.Contains(SuplierName));
            }
            if (!string.IsNullOrEmpty(StockName))
            {
                ilist = ilist.Where(i => i.StockName.Contains(StockName));
            }
            List<ShippingSelectMaterialDto> shippingSelectMaterialDtos = new List<ShippingSelectMaterialDto>();
            var materpacklist = _materialPackageRepository.GetEntityAlls().ToList();
            foreach (var item in ilist)
            {
                var material=_materialRepository.QueryEntityWhere(d => d.Code == item.MaterialCode);

                ShippingSelectMaterialDto dto = new ShippingSelectMaterialDto();
                dto.InventoryId = item.Id;
                dto.Code = item.MaterialCode;
                dto.Name = item.MaterialName;
                dto.SuplierName = item.SupplierName;
                dto.StockCode = item.StockCode;
                dto.StockName = item.StockName;
                dto.BatchNo = item.BatchNo;
                dto.ModelSpec = material.ModelSpec;
                dto.LocationName = item.LocationName;
                dto.UnitName = item.UnitName;
                dto.InvCount = item.AvailableQty;
                dto.PallBarcode = item.PalletBarcode;
                dto.LocationCode = item.LocationCode;
                dto.CreatedDate = item.CreateDate;
                
                if (Config.IsReplenishment == true)
                {
                    var materpackobj = materpacklist.FirstOrDefault(x => x.MaterialId == item.MaterialId);
                    if (materpackobj != null)
                    {
                        if (item.AreaCode.Contains('P'))
                        {
                            dto.InvCount = dto.InvCount / materpackobj.ConversionFactor;
                        }
                        else if (item.AreaCode.Contains('L'))
                        {
                            dto.UnitName = materpackobj.SubPackageUnitName;
                        }
                    }
                }
                shippingSelectMaterialDtos.Add(dto);
            }
            count = ilist.Count();
            var list = shippingSelectMaterialDtos.OrderByDescending(x => x.CreatedDate).Skip((pageIndex - 1) * pageSize).Take(pageSize);

            return list.ToList();
        }

        #region 一键选定
        public List<ShippingSelectMaterialDto>? GetSelectInventoryMaterialAll(int pageIndex, int pageSize, long? mid, decimal? outqty, string? arecode, out int count)
        {
            var ilist = _inventoryRepository.GetEntityAlls().Where(x => x.MaterialId == mid && x.IsLock == false && x.Status == 1);
            if (!ilist.Any())
            {
                count = 0;
                return null;
            }
            var zilist = ilist.Where(x => x.AreaCode.Contains("P"));
            var silist = ilist.Where(x => x.AreaCode.Contains("L"));
            var materpackobj = _materialPackageRepository.QueryEntityWhere(x => x.MaterialId == mid);

            List<ShippingSelectMaterialDto> shippingSelectMaterialDtos = new List<ShippingSelectMaterialDto>();
            if (materpackobj != null)
            {
                //可拆卸
                decimal? zqty = ilist.Where(x => x.AreaCode.Contains("P")).Sum(x => x.AvailableQty);
                decimal? sqty = ilist.Where(x => x.AreaCode.Contains("L")).Sum(x => x.AvailableQty);
                if (zqty + sqty < outqty)
                {
                    foreach (var item in ilist)
                    {
                        ShippingSelectMaterialDto dto = new ShippingSelectMaterialDto();
                        dto.InventoryId = item.Id;
                        dto.Code = item.MaterialCode;
                        dto.Name = item.MaterialName;
                        dto.UnitName = item.UnitName;
                        dto.InvCount = item.AvailableQty;
                        dto.PallBarcode = item.PalletBarcode;
                        dto.LocationCode = item.LocationCode;
                        dto.Qty = item.AvailableQty;
                        dto.CreatedDate = item.CreateDate;
                        if (item.AreaCode.Contains("P"))
                        {
                            dto.InvCount = dto.InvCount / materpackobj.ConversionFactor;
                            dto.Qty = dto.InvCount;
                        }
                        else if (item.AreaCode.Contains("L"))
                        {
                            dto.UnitName = materpackobj.SubPackageUnitName;
                        }
                        shippingSelectMaterialDtos.Add(dto);
                    }
                    count = shippingSelectMaterialDtos.Count();
                    var lists = shippingSelectMaterialDtos.Skip((pageIndex - 1) * pageSize).Take(pageSize);

                    return lists.ToList();
                }
                if (zqty >= outqty && outqty % materpackobj.ConversionFactor == 0)
                {
                    var zinvenlist = zilist.OrderBy(x => x.AvailableQty).ToList();
                    #region 待优化方式
                    //for (int i = 0; ;)
                    //{
                    //    if (outqty == 0)
                    //    {
                    //        break;
                    //    }
                    //    var obj = zinvenlist.FirstOrDefault(x => x.AvailableQty == outqty);
                    //    if (obj != null)
                    //    {
                    //        ShippingSelectMaterialDto dto = new ShippingSelectMaterialDto();
                    //        dto.InventoryId = obj.Id;
                    //        dto.Code = obj.MaterialCode;
                    //        dto.Name = obj.MaterialName;
                    //        dto.UnitName = obj.UnitName;
                    //        dto.InvCount = obj.AvailableQty / materpackobj.ConversionFactor;
                    //        dto.PallBarcode = obj.PalletBarcode;
                    //        dto.LocationCode = obj.LocationCode;
                    //        dto.Qty = dto.InvCount;
                    //        outqty -= obj.AvailableQty;
                    //        dto.CreatedDate = obj.CreateDate;
                    //        shippingSelectMaterialDtos.Add(dto);
                    //        break;
                    //    }
                    //    else
                    //    {
                    //        obj = zinvenlist.FirstOrDefault(x => x.AvailableQty < outqty);
                    //        if (obj != null)
                    //        {
                    //            ShippingSelectMaterialDto dto = new ShippingSelectMaterialDto();
                    //            dto.InventoryId = obj.Id;
                    //            dto.Code = obj.MaterialCode;
                    //            dto.Name = obj.MaterialName;
                    //            dto.UnitName = obj.UnitName;
                    //            dto.InvCount = obj.AvailableQty / materpackobj.ConversionFactor;
                    //            dto.PallBarcode = obj.PalletBarcode;
                    //            dto.LocationCode = obj.LocationCode;
                    //            dto.Qty = dto.InvCount;
                    //            outqty -= obj.AvailableQty;
                    //            dto.CreatedDate = obj.CreateDate;
                    //            shippingSelectMaterialDtos.Add(dto);
                    //            zinvenlist.Remove(obj);
                    //        }
                    //        else
                    //        {
                    //            obj = zinvenlist.FirstOrDefault(x => x.AvailableQty < outqty);
                    //            ShippingSelectMaterialDto dto = new ShippingSelectMaterialDto();
                    //            dto.InventoryId = obj.Id;
                    //            dto.Code = obj.MaterialCode;
                    //            dto.Name = obj.MaterialName;
                    //            dto.UnitName = obj.UnitName;
                    //            dto.InvCount = obj.AvailableQty / materpackobj.ConversionFactor;
                    //            dto.PallBarcode = obj.PalletBarcode;
                    //            dto.LocationCode = obj.LocationCode;
                    //            dto.Qty = dto.InvCount;
                    //            dto.CreatedDate = obj.CreateDate;
                    //            shippingSelectMaterialDtos.Add(dto);
                    //            break;
                    //        }
                    //    }
                    //}
                    #endregion
                    //等于0整件支持
                    foreach (var item in zinvenlist)
                    {
                        if (outqty == 0)
                        {
                            break;
                        }
                        ShippingSelectMaterialDto dto = new ShippingSelectMaterialDto();
                        dto.InventoryId = item.Id;
                        dto.Code = item.MaterialCode;
                        dto.Name = item.MaterialName;
                        dto.UnitName = item.UnitName;
                        dto.InvCount = item.AvailableQty / materpackobj.ConversionFactor;
                        dto.PallBarcode = item.PalletBarcode;
                        dto.LocationCode = item.LocationCode;
                        if (outqty >= item.AvailableQty)
                        {
                            dto.Qty = dto.InvCount;
                            outqty -= item.AvailableQty;
                            dto.CreatedDate = item.CreateDate;
                            shippingSelectMaterialDtos.Add(dto);
                        }
                        else
                        {
                            dto.Qty = outqty / materpackobj.ConversionFactor;
                            dto.CreatedDate = item.CreateDate;
                            shippingSelectMaterialDtos.Add(dto);
                            break;
                        }
                    }
                }
                else if (zqty + sqty >= outqty)
                {
                    decimal? soutqty = outqty % materpackobj.ConversionFactor;
                    decimal? zoutqty = 0;
                    if (zqty == 0)
                        soutqty = outqty;
                    else if (zqty < outqty - soutqty)
                    {
                        zoutqty = zqty;
                        soutqty = outqty - zoutqty;
                    }
                    else
                    {
                        zoutqty = outqty - soutqty;
                    }

                    var zinvenlist = zilist.OrderBy(x => x.AvailableQty).ToList();
                    foreach (var item in zinvenlist)
                    {
                        if (zoutqty == 0)
                        {
                            break;
                        }
                        ShippingSelectMaterialDto dto = new ShippingSelectMaterialDto();
                        dto.InventoryId = item.Id;
                        dto.Code = item.MaterialCode;
                        dto.Name = item.MaterialName;
                        dto.UnitName = item.UnitName;
                        dto.InvCount = item.AvailableQty / materpackobj.ConversionFactor;
                        dto.PallBarcode = item.PalletBarcode;
                        dto.LocationCode = item.LocationCode;
                        if (zoutqty >= item.AvailableQty)
                        {
                            dto.Qty = dto.InvCount;
                            zoutqty -= item.AvailableQty;
                            dto.CreatedDate = item.CreateDate;
                            shippingSelectMaterialDtos.Add(dto);
                        }
                        else
                        {
                            dto.Qty = zoutqty / materpackobj.ConversionFactor;
                            dto.CreatedDate = item.CreateDate;
                            shippingSelectMaterialDtos.Add(dto);
                            break;
                        }
                    }
                    var sinvenlist = silist.OrderBy(x => x.AvailableQty).ToList();
                    foreach (var item in sinvenlist)
                    {
                        if (soutqty == 0)
                        {
                            break;
                        }
                        ShippingSelectMaterialDto dto = new ShippingSelectMaterialDto();
                        dto.InventoryId = item.Id;
                        dto.Code = item.MaterialCode;
                        dto.Name = item.MaterialName;
                        dto.UnitName = materpackobj.SubPackageUnitName;
                        dto.InvCount = item.AvailableQty;
                        dto.PallBarcode = item.PalletBarcode;
                        dto.LocationCode = item.LocationCode;
                        if (soutqty >= item.AvailableQty)
                        {
                            dto.Qty = item.AvailableQty;
                            soutqty -= item.AvailableQty;
                            dto.CreatedDate = item.CreateDate;
                            shippingSelectMaterialDtos.Add(dto);
                        }
                        else
                        {
                            dto.Qty = soutqty;
                            dto.CreatedDate = item.CreateDate;
                            shippingSelectMaterialDtos.Add(dto);
                            break;
                        }
                    }
                }
                else
                {
                    var sinvenlist = silist.OrderBy(x => x.AvailableQty).ToList();
                    foreach (var item in sinvenlist)
                    {
                        if (outqty == 0)
                        {
                            break;
                        }
                        ShippingSelectMaterialDto dto = new ShippingSelectMaterialDto();
                        dto.InventoryId = item.Id;
                        dto.Code = item.MaterialCode;
                        dto.Name = item.MaterialName;
                        dto.UnitName = materpackobj.SubPackageUnitName;
                        dto.InvCount = item.AvailableQty;
                        dto.PallBarcode = item.PalletBarcode;
                        dto.LocationCode = item.LocationCode;
                        if (outqty >= item.AvailableQty)
                        {
                            dto.Qty = item.AvailableQty;
                            outqty -= item.AvailableQty;
                            dto.CreatedDate = item.CreateDate;
                            shippingSelectMaterialDtos.Add(dto);
                        }
                        else
                        {
                            dto.Qty = outqty;
                            dto.CreatedDate = item.CreateDate;
                            shippingSelectMaterialDtos.Add(dto);
                            break;
                        }
                    }
                }
            }
            else
            {
                ilist = ilist.Where(x => x.AreaCode.Contains("P"));
                if (ilist.Sum(x => x.AvailableQty) < outqty)
                {
                    count = 0;
                    return null;
                }
                var invenlist = ilist.OrderBy(x => x.AvailableQty).ToList();
                //不可拆卸
                foreach (var item in invenlist)
                {
                    if (outqty == 0)
                    {
                        break;
                    }
                    ShippingSelectMaterialDto dto = new ShippingSelectMaterialDto();
                    dto.InventoryId = item.Id;
                    dto.Code = item.MaterialCode;
                    dto.Name = item.MaterialName;
                    dto.UnitName = item.UnitName;
                    dto.InvCount = item.AvailableQty;
                    dto.PallBarcode = item.PalletBarcode;
                    dto.LocationCode = item.LocationCode;
                    if (outqty >= item.AvailableQty)
                    {
                        dto.Qty = item.AvailableQty;
                        outqty -= item.AvailableQty;
                        dto.CreatedDate = item.CreateDate;
                        shippingSelectMaterialDtos.Add(dto);
                    }
                    else
                    {
                        dto.Qty = outqty;
                        dto.CreatedDate = item.CreateDate;
                        shippingSelectMaterialDtos.Add(dto);
                        break;
                    }
                }
            }
            count = shippingSelectMaterialDtos.Count();
            var lists2 = shippingSelectMaterialDtos.Skip((pageIndex - 1) * pageSize).Take(pageSize);

            return lists2.ToList();
        }

        public List<ShippingSelectMaterialDto>? GetSelectInventoryMaterialAllNo(int pageIndex, int pageSize, long? mid, decimal? outqty, string? arecode, string? batchno, out int count)
        {
            var ilist = _inventoryRepository.GetEntityAlls().Where(x => x.MaterialId == mid && x.IsLock == false && x.Status == 1);
            if (!ilist.Any())
            {
                count = 0;
                return null;
            }
            if (!string.IsNullOrEmpty(arecode))
                ilist = ilist.Where(x => x.AreaCode.Contains(arecode));
            if (!string.IsNullOrEmpty(batchno))
                ilist = ilist.Where(x => x.BatchNo.Contains(batchno));
            List<ShippingSelectMaterialDto> shippingSelectMaterialDtos = new List<ShippingSelectMaterialDto>();
            var sinvenlist = ilist.OrderBy(x => x.AvailableQty).ToList();
            foreach (var item in sinvenlist)
            {
                if (outqty == 0)
                {
                    break;
                }
                ShippingSelectMaterialDto dto = new ShippingSelectMaterialDto();
                dto.InventoryId = item.Id;
                dto.Code = item.MaterialCode;
                dto.Name = item.MaterialName;
                dto.UnitName = item.UnitName;
                dto.InvCount = item.AvailableQty;
                dto.PallBarcode = item.PalletBarcode;
                dto.LocationCode = item.LocationCode;
                if (outqty >= item.AvailableQty)
                {
                    dto.Qty = item.AvailableQty;
                    outqty -= item.AvailableQty;
                    dto.CreatedDate = item.CreateDate;
                    shippingSelectMaterialDtos.Add(dto);
                }
                else
                {
                    dto.Qty = outqty;
                    dto.CreatedDate = item.CreateDate;
                    shippingSelectMaterialDtos.Add(dto);
                    break;
                }
            }
            count = shippingSelectMaterialDtos.Count();
            var lists2 = shippingSelectMaterialDtos.Skip((pageIndex - 1) * pageSize).Take(pageSize);

            return lists2.ToList();
        }
        #endregion
        public List<ShippingOrderDetailLockDto>? GetShippingOrderDetailLockDtoList(string? ordersn, string? materialkey, int status, int pageIndex, int pageSize, out int totalCount)
        {
            List<ShippingOrderDetailLockDto> shippingOrderDetailLockDtos = new List<ShippingOrderDetailLockDto>();
            var slist = _shippingOrderDetailRepository.GetEntityAlls();
            var sllist = _lockCellRepository.GetEntityAlls();
            if (!string.IsNullOrEmpty(ordersn))
                slist = slist.Where(x => x.OrderSn.Contains(ordersn));
            if (status < 8)
                sllist = sllist.Where(x => x.Status == status);

            if (!string.IsNullOrEmpty(materialkey))
                sllist = sllist.Where(x => x.MaterialCode.Contains(materialkey)||x.ModelSpec.Contains(materialkey));

            if (slist.Any())
            {
                var materpacklistQuery = _materialPackageRepository.GetEntityAll()
    .Select(x => new { x.MaterialId, x.ConversionFactor, x.SubPackageUnitName });
                var list = from a in slist
                           join b in sllist on a.Id equals b.OrderDetailId
                           join m in materpacklistQuery on b.MaterialId equals m.MaterialId into mJoin
                           from m in mJoin.DefaultIfEmpty()
                           select new ShippingOrderDetailLockDto
                           {
                               Id = a.Id,
                               OrderId = b.Id,
                               OrderSn = a.OrderSn,
                               BillType = a.BillType,
                               PurOrderLineNo = a.PurOrderLineNo,
                               Status = Config.IsReplenishment ? b.Status : a.Status,
                               AreaName = a.AreaName,
                               //计划生产名称
                               ProductName = a.ProductName,
                               ProductQty = a.ProductQty,
                               //为物料规格不是计划规格
                               ProductModelSpec = b.ModelSpec,
                               WorkShopName = a.DeptName,
                               MaterialCode = b.MaterialCode,
                               MaterialName = a.MaterialName,
                               BatchNo = a.BatchNo,
                               Capsule = (a.IsOnceOut == null || a.IsOnceOut == false) ? 0 : 1,
                               UnitName = Config.IsReplenishment ? (a.AreaCode.Contains('L') ? m.SubPackageUnitName : a.UnitName) : a.UnitName,
                               Qty = Config.IsReplenishment ? (a.AreaCode.Contains('L') ? a.Qty : (m == null ? b.OutQty : (b.OutQty / (m.ConversionFactor ?? 1)))) : a.Qty,
                               FinshDate = a.FinshDate,
                               CreateDate = a.CreateDate,
                               PurOrderNo = a.PurOrderNo,
                               CellName = b.CellName,
                               IsSuspend = a.IsSuspend,
                               PalletBarcode = b.PalletBarcode,
                               PackCode = b.PackCode,
                               CachePortCode = b.CachePortCode,
                               IsOutOrderReview = a.IsOutOrderReview,
                               IsPicking = b.IsPicking
                           };
                totalCount = list.Count();
                return list.OrderByDescending(x => x.CreateDate).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
            }
            totalCount = 0;
            return shippingOrderDetailLockDtos;

        }
        public bool ModifyPurOrderNo(List<ShippingOrderDetailLockDto> dt)
        {
            foreach (var item in dt)
            {
                var shippingOrderDetail =  _shippingOrderDetailRepository.QueryEntityWhere(d => d.Id == item.Id);

                if (shippingOrderDetail != null)
                {
                    shippingOrderDetail.PurOrderNo = "已同步";
                     _shippingOrderDetailRepository.UpdateAsync(shippingOrderDetail);
                }
                else
                {

                    return false;
                }
            }
            return  _unitOfWork.SaveChangesEntity();
        }
        public ShippingOrderDetail? GetShippingOrderDetailById(long id)
        {
            var sobj = _shippingOrderDetailRepository.QueryEntityById(id);
            if (sobj == null)
                return null;
            ShippingOrderDetail shippingOrderDetail = new ShippingOrderDetail();
            shippingOrderDetail = sobj;
            var slobjlist = _lockCellRepository.GetEntityWhereAll(x => x.OrderDetailId == sobj.Id);
            if (slobjlist.Any())
                sobj.LockCellList = slobjlist.ToList();
            return shippingOrderDetail;
        }

        public ShippingMaterialLookDto? GetShippingMaterialLookDtoById(long id)
        {
            var sobj = _shippingOrderDetailRepository.QueryEntityById(id);
            if (sobj == null)
                return null;
            ShippingMaterialLookDto shippingMaterialLookDto = new ShippingMaterialLookDto();
            shippingMaterialLookDto = mapper.Map<ShippingMaterialLookDto>(sobj);

            List<ShippingSelectMaterialDto> shippingSelectMaterialDtolist = new List<ShippingSelectMaterialDto>();

            var slockobj = _lockCellRepository.QueryEntityWhere(x => x.OrderDetailId == sobj.Id);

            if (slockobj == null)
            {
                return null;
            }
            var materpackobj = _materialPackageRepository.QueryEntityWhere(x => x.MaterialId == slockobj.MaterialId);
            ShippingSelectMaterialDto shippingSelectMaterialDto = new ShippingSelectMaterialDto();
            shippingSelectMaterialDto.Code = slockobj.MaterialCode;
            shippingSelectMaterialDto.Name = slockobj.MaterialName;
            if (Config.IsReplenishment)
            {
                if (sobj.AreaCode.Contains("P"))
                {
                    if (materpackobj != null)
                    {
                        shippingSelectMaterialDto.Qty = sobj.Qty / materpackobj.ConversionFactor;
                        shippingSelectMaterialDto.InvCount = slockobj.InventoryQty / materpackobj.ConversionFactor;
                    }
                    else
                    {
                        shippingSelectMaterialDto.Qty = sobj.Qty;
                        shippingSelectMaterialDto.InvCount = slockobj.InventoryQty;
                    }
                    shippingSelectMaterialDto.UnitName = sobj.UnitName;

                }
                else
                {
                    shippingSelectMaterialDto.Qty = sobj.Qty;
                    shippingSelectMaterialDto.InvCount = slockobj.InventoryQty;
                    if (materpackobj != null)
                        shippingSelectMaterialDto.UnitName = materpackobj.SubPackageUnitName;
                    else
                        shippingSelectMaterialDto.UnitName = sobj.UnitName;
                }
            }
            else
            {
                shippingSelectMaterialDto.Qty = sobj.Qty;
                shippingSelectMaterialDto.InvCount = slockobj.InventoryQty;
                shippingSelectMaterialDto.UnitName = sobj.UnitName;
            }
            var modelspec = string.Empty;
            if (!string.IsNullOrEmpty(slockobj.MaterialCode))
            {
                var material=_materialRepository.QueryEntityWhere(d => d.Code == slockobj.MaterialCode);
                modelspec = material.ModelSpec;
            }
         
            shippingSelectMaterialDto.Status = slockobj.Status;
            shippingSelectMaterialDto.PackCode = slockobj.PackCode;
            shippingSelectMaterialDto.CachePortCode = slockobj.CachePortCode;
            shippingSelectMaterialDto.PartSendDate = slockobj.PartSendDate;
            shippingSelectMaterialDto.PallBarcode = slockobj.PalletBarcode;
            shippingSelectMaterialDto.InventoryId = (long)slockobj.InventoryId;
            shippingSelectMaterialDto.LocationCode = slockobj.CellCode;
            shippingSelectMaterialDto.ModelSpec = modelspec;
            shippingSelectMaterialDtolist.Add(shippingSelectMaterialDto);
            shippingMaterialLookDto.ShippingSelectMaterialDtos = shippingSelectMaterialDtolist;
            return shippingMaterialLookDto;
        }

        public List<ShippingOrderDetail> GetShippingOrderDetailList(string? ordersn, string? materialkey, int status, int pageIndex, int pageSize, out int totalCount)
        {
            var slist = _shippingOrderDetailRepository.GetEntityAlls();

            if (!string.IsNullOrEmpty(ordersn))
                slist = slist.Where(x => x.OrderSn.Contains(ordersn));
            if (status < 8)
                slist = slist.Where(x => x.Status == status);

            if (!string.IsNullOrEmpty(materialkey))
                slist = slist.Where(x => x.MaterialCode.Contains(materialkey) || x.MaterialName.Contains(materialkey));

            var list = _shippingOrderDetailRepository.GetEntityAlls(slist, pageIndex, pageSize, out totalCount, x => x.CreateDate, false);
            return list.ToList();
        }

        public bool UpdShippingOrderDetail(ShippingOrderDetail m, out string message)
        {
            message = string.Empty;
            bool result = false;
            bool ispick = m.BillType == 1 ? false : true;
            if (m.Status == 3 || m.Status == 4)
            {
                message = "作业中和已完成的单据不可修改！";
                return false;
            }
            if (m.SupplierId != null)
            {
                var sobj = _supplierRepository.QueryEntityById((long)m.SupplierId);
                if (sobj != null)
                {
                    m.SupplierName = sobj.Name;
                }
                else
                {
                    message = "供应商不存在或者已被禁用！";
                    return false;
                }
            }
            if (m.CustomerId != null)
            {
                var cobj = _customerRepository.QueryEntityById((long)m.CustomerId);
                if (cobj != null)
                {
                    m.CustomerName = cobj.Name;
                }
                else
                {
                    message = "客户不存在或者已被禁用！";
                    return false;
                }
            }
            if (!string.IsNullOrEmpty(m.AreaCode))
            {
                var aobj = _areaRepository.QueryEntityWhere(x => x.Code == m.AreaCode);
                if (aobj == null || aobj.Status != 1)
                {
                    message = "库区不存在或者已被禁用！";
                    return false;
                }
            }
            m.Status = 0;
            m.ShippedQty = 0;
            m.SourceType = 0;
            //是否挂起-逻辑待处理
            m.IsSuspend = false;
            m.Qty = 0;
            try
            {
                var materialpacklist = _materialPackageRepository.GetEntityAlls();
                _unitOfWork.BeginTransaction();
                var slobj = _lockCellRepository.QueryEntityWhere(x => x.OrderDetailId == m.Id);
                if (slobj != null)
                {
                    _lockCellRepository.DelEntity(slobj);
                    if (slobj.InventoryId == null)
                    {
                        message = "库存信息有误！";
                        _unitOfWork.RollbackChanges();
                        return false;
                    }
                    var uinvobj = _inventoryRepository.QueryEntityById((long)slobj.InventoryId);
                    if (uinvobj != null)
                    {
                        uinvobj.IsLock = false;
                        uinvobj.Status = 1;
                        uinvobj.PickedQty -= slobj.OutQty;
                        uinvobj.AllocateQty -= slobj.OutQty;
                        uinvobj.Remark = string.Empty;
                    }
                }
                foreach (var item in m.LockCellList)
                {
                    if (item.InventoryId == null)
                    {
                        message = "找不到库存信息！";
                        _unitOfWork.RollbackChanges();
                        return false;
                    }
                    var invobj = _inventoryRepository.QueryEntityById((long)item.InventoryId);
                    if (invobj == null)
                    {
                        message = "库存信息有误！";
                        _unitOfWork.RollbackChanges();
                        return false;
                    }
                    m.AreaCode = invobj.AreaCode;
                    m.AreaName = invobj.AreaName;
                    m.WarehouseId = invobj.WarehouseId;
                    m.WarehouseCode = invobj.WarehouseCode;
                    m.WarehouseName = invobj.WarehouseName;
                    m.MaterialId = invobj.MaterialId == null ? 0 : Convert.ToInt64(invobj.MaterialId);
                    m.MaterialName = invobj.MaterialName;
                    m.MaterialCode = invobj.MaterialCode;
                    m.MaterialTypeCode = invobj.MaterialTypeCode;
                    m.UnitId = invobj.UnitId;
                    m.UnitName = invobj.UnitName;
                    m.Qty = item.OutQty;
                    m.BatchNo = invobj.BatchNo;
                    if (Config.IsReplenishment == true)
                    {
                        if (invobj.AreaCode.Contains('L'))
                        {
                            //散区
                            if (item.OutQty > item.InventoryQty)
                            {
                                var frominobj = _inventoryRepository.QueryEntityWhere(x => x.AreaCode.Contains('P') && x.MaterialId == invobj.MaterialId && x.BatchNo == invobj.BatchNo && x.Status == 1 && x.IsLock == false && item.OutQty - invobj.AvailableQty <= x.AvailableQty);
                                if (frominobj == null)
                                {
                                    m.Qty = invobj.AvailableQty;
                                    item.OutQty = m.Qty;
                                    invobj.PickedQty += m.Qty;
                                    invobj.AllocateQty += m.Qty;
                                    invobj.IsLock = true;
                                }
                                else
                                {
                                    var matelpackobj = materialpacklist.FirstOrDefault(x => x.MaterialId == invobj.MaterialId);
                                    if (matelpackobj == null)
                                    {
                                        message = "该物资打包明细有误！";
                                        return false;
                                    }
                                    invobj.PickedQty += item.OutQty;
                                    invobj.AllocateQty += item.OutQty;
                                    invobj.IsLock = true;
                                    m.Qty = item.OutQty;
                                    m.IsSuspend = true;
                                    invobj.Status = 5;
                                    invobj.Remark = "补货";
                                    frominobj.IsLock = true;
                                    frominobj.AllocateQty = matelpackobj.ConversionFactor;
                                    frominobj.PickedQty += matelpackobj.ConversionFactor;
                                    frominobj.Status = 5;
                                    ShippingReplenishment shippingReplenishment = new ShippingReplenishment
                                    {
                                        OrderId = m.Id,
                                        OrdeSn = m.OrderSn,
                                        BillType = 1,
                                        MaterialId = invobj.MaterialId,
                                        MaterialName = invobj.MaterialName,
                                        FromWhId = frominobj.WarehouseId,
                                        FromWhCode = frominobj.WarehouseCode,
                                        FromWhName = frominobj.WarehouseName,
                                        FromAreaId = frominobj.AreaId,
                                        FromAreaCode = frominobj.AreaCode,
                                        FromAreaName = frominobj.AreaName,
                                        FromInventoryId = frominobj.Id,
                                        FromCellId = frominobj.LocationId,
                                        FromCellCode = frominobj.LocationCode,
                                        FromCellName = frominobj.LocationName,
                                        FromCellDepthIndex = frominobj.LocationDepth,
                                        FromPalletBarcode = frominobj.PalletBarcode,
                                        ToWhId = invobj.WarehouseId,
                                        ToWhCode = invobj.WarehouseCode,
                                        ToWhName = invobj.WarehouseName,
                                        ToAreaId = invobj.AreaId,
                                        ToAreaCode = invobj.AreaCode,
                                        ToAreaName = invobj.AreaName,
                                        ToInventoryId = invobj.Id,
                                        ToCellId = invobj.LocationId,
                                        ToCellCode = invobj.LocationCode,
                                        ToCellName = invobj.LocationName,
                                        ToCellDepthIndex = invobj.LocationDepth,
                                        ToPalletBarcode = invobj.PalletBarcode,
                                        AddQty = matelpackobj.ConversionFactor,
                                        SubtractQty = matelpackobj.ConversionFactor,
                                        Remark = "从" + frominobj.LocationName + "减出 " + "1" + invobj.UnitName + " 补到" + invobj.LocationName
                                    };
                                    _shippingReplenishmentRepository.AddEntity(shippingReplenishment);
                                }
                            }
                            else
                            {
                                m.Qty = item.OutQty;
                                invobj.PickedQty += item.OutQty;
                                invobj.AllocateQty += item.OutQty;
                                invobj.IsLock = true;
                            }
                        }
                        else
                        {
                            var matelpackobj = materialpacklist.FirstOrDefault(x => x.MaterialId == invobj.MaterialId);

                            invobj.IsLock = true;
                            if (item.OutQty > item.InventoryQty)
                            {
                                message = "出库数量不能大于库存数量！";
                                _unitOfWork.RollbackChanges();
                                return false;
                            }
                            if (matelpackobj != null && matelpackobj.ConversionFactor != null)
                                item.OutQty = item.OutQty * matelpackobj.ConversionFactor;
                            m.Qty = item.OutQty;
                            invobj.PickedQty += item.OutQty;
                            invobj.AllocateQty += item.OutQty;
                        }
                    }
                    else
                    {
                        if (item.OutQty > item.InventoryQty)
                        {
                            message = $"物资{invobj.MaterialCode}出库数量不能大于库存数量！";
                            _unitOfWork.RollbackChanges();
                            return false;
                        }
                        else
                            m.Qty = item.OutQty;
                        invobj.PickedQty += item.OutQty;
                        invobj.AllocateQty += item.OutQty;
                        invobj.IsLock = true;
                    }
                    _shippingOrderDetailRepository.UpdEntity(m);
                    item.OrderDetailId = m.Id;
                    item.OrdeSn = m.OrderSn;
                    item.CellId = invobj.LocationId;
                    item.CellCode = invobj.LocationCode;
                    item.CellName = invobj.LocationName;
                    item.CellDepthIndex = invobj.LocationDepth;
                    item.WhId = invobj.WarehouseId;
                    item.PalletBarcode = invobj.PalletBarcode;
                    item.MaterialId = invobj.MaterialId;
                    item.MaterialCode = invobj.MaterialCode;
                    item.MaterialName = invobj.MaterialName;
                    item.MaterialKeyId = invobj.MaterialKeyId;
                    item.RoutewayId = invobj.RoutewayId;
                    item.BatchNo = invobj.BatchNo;
                    item.InventoryQty = invobj.AvailableQty;
                    if (item.OutQty <= 0)
                    {
                        message = "出库数量不能为0！";
                        _unitOfWork.RollbackChanges();
                        return false;
                    }
                    if (item.OutQty % 1 != 0)
                    {
                        message = "出库数量不能是小数";
                        _unitOfWork.RollbackChanges();
                        return false;
                    }
                    if (!ispick)
                    {
                        if (m.Qty == invobj.AvailableQty)
                            m.BillType = 1;
                        else
                            m.BillType = 2;
                    }
                    _lockCellRepository.AddEntity(item);
                    result = _unitOfWork.SaveChangesEntity();
                    if (result == false)
                        break;
                }
                if (result)
                {
                    _unitOfWork.CommitChanges();
                    return true;
                }
                _unitOfWork.RollbackChanges();
                return false;
            }
            catch (Exception)
            {
                _unitOfWork.RollbackChanges();
                throw;
            }
        }

        public List<ShippingOrderDetail> GetShippingOrderDetailByOrder(string order)
        {
            var slist = _shippingOrderDetailRepository.GetEntityAlls().Where(x => x.Status == 4);

            var sllist = _lockCellRepository.GetEntityAlls().Where(x => x.OrdeSn == order && x.Status == 1);

            var list = from a in slist
                       join b in sllist
                       on a.Id equals b.OrderDetailId
                       select a;

            return list.ToList();
        }
        #endregion

        #region PDA
        public List<ShippingOrderDetailGroupDTO> GetShippingOrderDetailGroup(string key, int pageIndex, int pageSize, out int totalCount)
        {
            var shippingOrderDetails = _shippingOrderDetailRepository.GetEntityAlls()
                .Where(s => s.Status < 4 && s.IsSuspend == false);

            if (!string.IsNullOrEmpty(key))
            {
                shippingOrderDetails = shippingOrderDetails.Where(x => x.MaterialCode.Contains(key));
            }
            var lockCellslist = _lockCellRepository.GetEntityAlls().Where(x => x.Status == 0);
            //var shippingOrderDetailLookup = shippingOrderDetails.ToLookup(s => s.OrderSn);

            //var lockCells = _lockCellRepository.GetEntityAlls().ToDictionary(lc => lc.OrderDetailId);

            //List<ShippingOrderDetailGroupDTO> resList = new List<ShippingOrderDetailGroupDTO>();
            //foreach (var group in shippingOrderDetailLookup)
            //{
            //    var shippingOrderDetailGroupDTO = new ShippingOrderDetailGroupDTO
            //    {
            //        OrderSn = group.Key,
            //        CheckedAll = false,
            //        LockCells = new List<ShippingLockCell>()
            //    };

            //    foreach (var detail in group)
            //    {
            //        if (lockCells.TryGetValue(detail.Id, out var lockCell))
            //        {
            //            shippingOrderDetailGroupDTO.LockCells.Add(lockCell);
            //        }
            //    }

            //    resList.Add(shippingOrderDetailGroupDTO);
            //}
            var shippingOrderDetailLookup = shippingOrderDetails.ToList().GroupBy(s => s.OrderSn);
            List<ShippingOrderDetailGroupDTO> resList = new List<ShippingOrderDetailGroupDTO>();
            foreach (var item in shippingOrderDetailLookup)
            {
                ShippingOrderDetailGroupDTO? shippingOrderDetailGroupDTO = new ShippingOrderDetailGroupDTO();
                shippingOrderDetailGroupDTO.OrderSn = item.Key;
                shippingOrderDetailGroupDTO.CheckedAll = false;
                shippingOrderDetailGroupDTO.LockCells = new List<ShippingLockCell>();
                var lockCells = lockCellslist.Where(x => x.OrdeSn == item.Key);
                if (!lockCells.Any())
                    continue;
                shippingOrderDetailGroupDTO.LockCells = lockCells.ToList();
                resList.Add(shippingOrderDetailGroupDTO);
            }
            totalCount = resList.Count;
            resList = resList.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();

            return resList;
        }

        #region 原来的
        //public bool StartShippingOrderDetail(List<SubmitOutListDTO> m, out string message)
        //{
        //    message = string.Empty;
        //    try
        //    {
        //        bool result = false;
        //        bool tresult = false;
        //        Dictionary<string, int> skeyValuePairs = new Dictionary<string, int>();
        //        Dictionary<string, string> tkeyValuePairs = new Dictionary<string, string>();
        //        var materpacklist = _materialPackageRepository.GetEntityAlls().ToList();
        //        _unitOfWork.BeginTransaction();
        //        foreach (var item in m)
        //        {
        //            //物料id
        //            long materid = 0;
        //            //托盘条码
        //            string pacode = item.PalletBarcode;
        //            int? billtype;
        //            var lockobj = _lockCellRepository.QueryEntityById(item.OrderDetId);
        //            if (lockobj == null)
        //            {
        //                message = "未查询到出库单详情";
        //                _unitOfWork.RollbackChanges();
        //                return false;
        //            }
        //            // 出库单数量修改 状态修改
        //            if (lockobj.OrderDetailId == null)
        //            {
        //                message = "出库单信息有误！";
        //                _unitOfWork.RollbackChanges();
        //                return false;
        //            }
        //            if (lockobj.Status == 3)
        //            {
        //                message = "当前任务正在作业中！";
        //                _unitOfWork.RollbackChanges();
        //                return false;
        //            }
        //            if (lockobj.Status == 4)
        //            {
        //                message = "当前任务已完成！";
        //                _unitOfWork.RollbackChanges();
        //                return false;
        //            }
        //            var materpackobj = materpacklist.FirstOrDefault(x => x.MaterialId == lockobj.MaterialId);
        //            lockobj.Status = 3;
        //            var shippingOrderDetail = _shippingOrderDetailRepository.QueryEntityById((long)lockobj.OrderDetailId);
        //            if (shippingOrderDetail == null)
        //            {
        //                message = "获取出库单信息失败！";
        //                _unitOfWork.RollbackChanges();
        //                return false;
        //            }
        //            if (shippingOrderDetail.Status == 4)
        //            {
        //                message = "当前出库单已完成！";
        //                _unitOfWork.RollbackChanges();
        //                return false;
        //            }
        //            if (shippingOrderDetail.IsSuspend == true)
        //            {
        //                message = "挂起任务无法执行！";
        //                _unitOfWork.RollbackChanges();
        //                return false;
        //            }
        //            billtype = shippingOrderDetail.BillType;
        //            shippingOrderDetail.Status = 3;
        //            materid = lockobj.MaterialId == null ? 0 : Convert.ToInt64(lockobj.MaterialId);
        //            var cellobj = _cellRepository.QueryEntityWhere(x => x.Code == lockobj.CellCode);
        //            if (cellobj == null)
        //            {
        //                message = "未查询到仓位" + lockobj.CellCode;
        //                _unitOfWork.RollbackChanges();
        //                return false;
        //            }
        //            if (cellobj.Status != 1)
        //            {
        //                message = "当前仓位已被禁用！";
        //                _unitOfWork.RollbackChanges();
        //                return false;
        //            }
        //            if (cellobj.RoutewayId == null)
        //            {
        //                message = "找不到该仓位所属的巷道！";
        //                _unitOfWork.RollbackChanges();
        //                return false;
        //            }
        //            var rouwatobj = _routewayRepository.QueryEntityById((long)cellobj.RoutewayId);
        //            if (rouwatobj != null && rouwatobj.Status != 1)
        //            {
        //                message = "当前巷道已被禁用！";
        //                _unitOfWork.RollbackChanges();
        //                return false;
        //            }
        //            long? invid = lockobj.InventoryId;
        //            if (invid == null)
        //            {
        //                message = "获取库存id有误！";
        //                _unitOfWork.RollbackChanges();
        //                return false;
        //            }
        //            Inventory? inventoryModel = _inventoryRepository.QueryEntityById((long)invid);
        //            //状态修改出库在途         
        //            if (inventoryModel == null)
        //            {
        //                message = "获取库存信息失败！";
        //                _unitOfWork.RollbackChanges();
        //                return false;
        //            }
        //            if (materpackobj != null && materpackobj.ConversionFactor > 0 && inventoryModel.AreaCode == "1")
        //                item.Qty = (decimal)(item.Qty * materpackobj.ConversionFactor);
        //            if (inventoryModel.AvailableQty < item.Qty)
        //            {
        //                message = "库存数量不足！";
        //                _unitOfWork.RollbackChanges();
        //                return false;
        //            }
        //            inventoryModel.Status = 4;
        //            #region 如果浅深位有货物产生移库操作
        //            if (inventoryModel.AreaCode == "2")
        //            {
        //                //排
        //                string rows = inventoryModel.LocationCode.Substring(7, 1);

        //                if (string.IsNullOrEmpty(rows))
        //                {
        //                    message = "获取仓位排失败！";
        //                    return false;
        //                }
        //                if (rows == "3")
        //                {
        //                    string modifiedcellcode = inventoryModel.LocationCode.Substring(0, 7) + "2" + inventoryModel.LocationCode.Substring(8, 5) + "1";
        //                    var inventorycell = _inventoryRepository.QueryEntityWhere(x => x.LocationCode == modifiedcellcode);
        //                    if (inventorycell != null)
        //                    {
        //                        if (!tkeyValuePairs.ContainsKey(inventorycell.PalletBarcode))
        //                            tkeyValuePairs.Add(inventorycell.PalletBarcode, inventorycell.LocationCode);
        //                        tresult = ShippingTransferBinInventory(inventoryModel.LocationCode, inventorycell.LocationCode, inventorycell.AreaCode, inventorycell.PalletBarcode, out message);
        //                        if (!tresult)
        //                        {
        //                            break;
        //                        }
        //                    }
        //                    tresult = true;
        //                }
        //                else
        //                    tresult = true;
        //                if (!tresult)
        //                {
        //                    return false;
        //                }
        //            }
        //            #endregion
        //            var inventorylist = _inventoryRepository.GetEntityWhereAll(x => x.PalletBarcode == pacode && x.Status == 1);
        //            if (inventorylist.Any())
        //            {
        //                foreach (var item2 in inventorylist)
        //                {
        //                    item2.IsLock = true;
        //                    item2.Status = 4;
        //                    _inventoryRepository.UpdEntity(item2);
        //                }
        //            }



        //            #region 添加指令
        //            Instruct inobj = new Instruct();
        //            inobj.WarehouseCode = inventoryModel.WarehouseCode;
        //            inobj.Status = 2;
        //            inobj.FromLocation = item.StationCode;
        //            inobj.ToLocation = inventoryModel.LocationCode;
        //            inobj.WorkDeviceType = 1;
        //            if (billtype == 2)
        //                inobj.InstructType = 6;
        //            else
        //                inobj.InstructType = 2;
        //            inobj.Action = 0;
        //            inobj.RelatedOrderId = shippingOrderDetail.Id;
        //            inobj.ExpectedToLocation = inventoryModel.LocationCode;
        //            inobj.InstructIndex = 1;
        //            inobj.PalletBarcode = pacode;
        //            inobj.ScanedBarcode = pacode;
        //            inobj.Priority = 9999;
        //            inobj.Qty = item.Qty;
        //            inobj.FinishedQty = 0;
        //            inobj.BusinessType = (int)EmBusinessType.Out;
        //            inobj.RelatedOrderDetailId = lockobj.Id;
        //            inobj.CreateUserId = item.NowUserId;
        //            inobj.CreateUserName = item.NowUserName;
        //            _instructRepository.AddEntity(inobj);
        //            #endregion
        //            #region 添加下架单
        //            string str = DateTime.Now.ToString("yyyyMMddHHmmssfff");
        //            string pickCode = "OUT" + str;
        //            PickingOrder pickOrder = new PickingOrder();
        //            pickOrder.Id = YitIdHelper.NextId();
        //            pickOrder.Code = pickCode;
        //            pickOrder.WarehouseCode = inventoryModel.WarehouseCode;
        //            pickOrder.WarehouseName = inventoryModel.WarehouseName;
        //            if (billtype == 2)
        //                pickOrder.BillType = 2;
        //            else
        //                pickOrder.BillType = 1;
        //            pickOrder.DescAddress = item.DescAddress;
        //            pickOrder.PalletBarcode = pacode;
        //            pickOrder.Roadway = cellobj.RoutewayId.ToString();
        //            pickOrder.LocationCode = cellobj.Code;
        //            pickOrder.LocationDepth = cellobj.DepthIndex;
        //            pickOrder.Status = 4;
        //            pickOrder.Qty = item.Qty;
        //            pickOrder.MaterialId = materid;
        //            pickOrder.MaterialCode = lockobj.MaterialCode;
        //            pickOrder.MaterialName = lockobj.MaterialName;
        //            pickOrder.MaterialKeyId = inventoryModel.MaterialKeyId;
        //            pickOrder.BatchNo = inventoryModel.BatchNo;
        //            pickOrder.SourceType = 2;
        //            pickOrder.RelatedOrderDetailId = item.OrderDetId;
        //            pickOrder.CreateDate = DateTime.Now;
        //            if (inventoryModel.AreaCode == "2")
        //            {
        //                if (!skeyValuePairs.ContainsKey(pacode))
        //                    skeyValuePairs.Add(pacode, 1);
        //            }
        //            _pickingOrderRepository.AddEntity(pickOrder);
        //            PickingOrderDetail pickOrderDetail = new PickingOrderDetail();
        //            pickOrderDetail.Id = YitIdHelper.NextId();
        //            pickOrderDetail.OrderId = pickOrder.Id;
        //            pickOrderDetail.PalletBarcode = pacode;
        //            pickOrderDetail.MaterialBarcode = lockobj.MaterialCode;
        //            _pickingOrderDetailRepository.AddEntity(pickOrderDetail);
        //            #endregion
        //            result = _unitOfWork.SaveChangesEntity();
        //            if (!result)
        //            {
        //                message = "出库解绑失败";
        //                return false;
        //            }
        //            if (cellobj.AreaCode == "1")
        //                result = StaticFinishShippingOrderDetail(pickCode, out message);
        //        }
        //        if(!tresult)
        //        {
        //            _unitOfWork.RollbackChanges();
        //            return false;
        //        }
        //        if (result)
        //        {
        //            if (Config.IsDev == false)
        //            {
        //                var putlist = _putawayOrderRepository.GetEntityWhereAll(x => x.Status == 4 && x.SourceType == 3);
        //                foreach (var item in tkeyValuePairs)
        //                {
        //                    var putobj = putlist.FirstOrDefault(x => x.PalletBarcode == item.Key);
        //                    if (putobj == null)
        //                        continue;
        //                    WcsTaskDto wcsTaskDto = new WcsTaskDto
        //                    {
        //                        TaskCode = putobj.Code,
        //                        TaskType = "2",
        //                        StartPoint = item.Value,
        //                        EndPoint = putobj.LocationCode
        //                    };
        //                    var wcsresult = _wcsHttpClient.OutTaskApi(wcsTaskDto);
        //                    if (wcsresult.ReturnStatus == 1)
        //                    {
        //                        message = wcsresult.ReturnInfo;
        //                        _unitOfWork.RollbackChanges();
        //                        return false;
        //                    }
        //                }
        //                var picklist = _pickingOrderRepository.GetEntityWhereAll(x => x.Status == 4 && x.SourceType == 2);
        //                foreach (var item in skeyValuePairs)
        //                {
        //                    var pickobj = picklist.FirstOrDefault(x => x.PalletBarcode == item.Key);
        //                    if (pickobj == null)
        //                        continue;
        //                    WcsTaskDto wcsTaskDto = new WcsTaskDto
        //                    {
        //                        TaskCode = pickobj.Code,
        //                        TaskType = "2",
        //                        StartPoint = pickobj.LocationCode
        //                    };
        //                    var wcsresult = _wcsHttpClient.OutTaskApi(wcsTaskDto);
        //                    if (wcsresult.ReturnStatus == 1)
        //                    {
        //                        message = wcsresult.ReturnInfo;
        //                        _unitOfWork.RollbackChanges();
        //                        return false;
        //                    }
        //                }
        //            }
        //            message = "操作成功！";
        //            _unitOfWork.CommitChanges();
        //            return true;
        //        }
        //        _unitOfWork.RollbackChanges();
        //        return false;
        //    }
        //    catch (Exception)
        //    {
        //        _unitOfWork.RollbackChanges();
        //        throw;
        //    }

        //}
        //#region 出库产生移库逻辑处理
        //private bool ShippingTransferBinInventory(string fromcellcode, string trancellcode, string acode, string pacode, out string message)
        //{
        //    message = string.Empty;
        //    #region 修改库存状态
        //    var toCell = GetCellCode(acode, out message);
        //    if (toCell == null)
        //    {
        //        message = "目标仓位不存在或者已被占用";
        //        return false;
        //    }
        //    else
        //    {
        //        toCell.FullStatus = 1;
        //        toCell.IsLock = true;
        //        toCell.BusinessType = 1;
        //        toCell.ModifyDate = DateTime.Now;
        //        _cellRepository.UpdEntity(toCell);
        //    }
        //    bool isshipplost = false;
        //    var slocklist = _lockCellRepository.GetEntityWhereAll(x => x.CellCode == trancellcode && x.Status == 0).ToList();
        //    foreach (var item2 in slocklist)
        //    {
        //        //标记状态列
        //        item2.CellId = toCell.Id;
        //        item2.CellCode = toCell.Code;
        //        item2.CellName = toCell.Name;
        //        item2.Status = 3;
        //        isshipplost = true;
        //        _lockCellRepository.UpdEntity(item2);
        //    }
        //    var tinventorylist = _inventoryRepository.GetEntityWhereAll(it => it.LocationCode == trancellcode).ToList();
        //    foreach (var inventory in tinventorylist)
        //    {
        //        inventory.LocationId = toCell.Id;
        //        inventory.LocationName = toCell.Name;
        //        inventory.LocationCode = toCell.Code;
        //        inventory.LocationDepth = toCell.DepthIndex;
        //        inventory.LocationLineNo = toCell.LineNo;
        //        inventory.LocationLayerNo = toCell.LayerNo;
        //        inventory.LocationColumnNo = toCell.ColumnNo;
        //        inventory.Status = 2;
        //        inventory.LocationHeightType = toCell.HeightType;
        //        inventory.IsLock = true;
        //        inventory.RoutewayId = toCell.RoutewayId;
        //        inventory.ErplocationCode = toCell.Erpcode;
        //        if (isshipplost)
        //            inventory.Remark = "系统移库";
        //        _inventoryRepository.UpdEntity(inventory);
        //        #region 关联的入库单做处理
        //        if (inventory.RelatedOrderDetailId == null)
        //        {
        //            message = "关联的入库单id有误！";
        //            return false;
        //        }
        //        var revingobj = _receivingOrderDetailRepository.QueryEntityById((long)inventory.RelatedOrderDetailId);
        //        if (revingobj == null)
        //        {
        //            message = "入库单明细不存在或已被删除";
        //            return false;
        //        }
        //        #region 指令管理
        //        Instruct instruct = null;
        //        instruct = new Instruct
        //        {
        //            WarehouseCode = toCell.WhCode,
        //            Status = 2,
        //            FromLocation = trancellcode,
        //            ToLocation = toCell.Code,
        //            StackingStorageId = 0,
        //            WorkDeviceType = 1,
        //            InstructType = 3,
        //            Action = 0,
        //            RelatedOrderId = revingobj.Id,
        //            RelatedOrderDetailId = 0,
        //            DeviceCode = "",
        //            ExpectedToLocation = toCell.Code,
        //            InstructIndex = 1,
        //            PalletBarcode = pacode,
        //            ScanedBarcode = pacode,
        //            Priority = 9999,
        //            Qty = inventory.AvailableQty == null ? 0 : (decimal)inventory.AvailableQty,
        //            FinishedQty = 0,
        //            CreateDate = DateTime.Now,
        //            BusinessType = (int)EmBusinessType.Move,
        //            BillType = (int)revingobj.BillType.GetValueOrDefault(),
        //        };
        //        _instructRepository.AddEntity(instruct);
        //        #endregion
        //        #endregion


        //        #endregion
        //        #region 上架单
        //        string tstr = DateTime.Now.ToString("yyyyMMddHHmmssfff");
        //        string traawayCode = "TRA" + tstr;
        //        PutawayOrder putawayOrder = new PutawayOrder();
        //        putawayOrder.Id = YitIdHelper.NextId();
        //        putawayOrder.Code = traawayCode;
        //        putawayOrder.RelatedOrderDetailId = tinventorylist.First().RelatedOrderDetailId;
        //        putawayOrder.StackingStorageId = 0;
        //        putawayOrder.PalletBarcode = tinventorylist.First().PalletBarcode;
        //        putawayOrder.LocationCode = toCell.Code;
        //        putawayOrder.LocationDepth = toCell.DepthIndex == 0 ? null : toCell.DepthIndex;
        //        putawayOrder.Status = 4;
        //        putawayOrder.Qty = tinventorylist.First().AvailableQty;
        //        putawayOrder.CreateDate = DateTime.Now;
        //        putawayOrder.MaterialId = tinventorylist.First().MaterialId;
        //        putawayOrder.MaterialCode = tinventorylist.First().MaterialCode;
        //        putawayOrder.MaterialName = tinventorylist.First().MaterialName;
        //        putawayOrder.MaterialKeyId = tinventorylist.First().MaterialKeyId;
        //        putawayOrder.BatchNo = tinventorylist.First().BatchNo;
        //        putawayOrder.CreateUserId = 0;
        //        putawayOrder.CreateUserName = "系统";
        //        putawayOrder.SourceType = 3;
        //        putawayOrder.SiteCode = "";
        //        _putawayOrderRepository.AddEntity(putawayOrder);
        //    }
        //    var pallobj = _palletRepository.QueryEntityWhere(x => x.LocationCode == trancellcode);
        //    if (pallobj != null)
        //    {
        //        pallobj.LocationName = toCell.Name;
        //        pallobj.LocationCode = toCell.Code;
        //    }

        //    #endregion
        //    return _unitOfWork.SaveChangesEntity();
        //}

        //private DFGK_WMS.Model.Models.Cell? GetCellCode(string acode, out string message)
        //{
        //    message = string.Empty;
        //    if (string.IsNullOrEmpty(acode))
        //    {
        //        message = "库区编码有误！";
        //        return null;
        //    }
        //    DFGK_WMS.Model.Models.Cell? cellobj = new DFGK_WMS.Model.Models.Cell();
        //    //获取所有库区
        //    var areaobj = _areaRepository.QueryIsEntityWhere(x => x.Code == acode && x.Status == 1);
        //    if (areaobj == null || areaobj.WhId == null)
        //    {
        //        message = "库区不存在或已被禁用!";
        //        return null;
        //    }
        //    long? wid = areaobj.WhId;
        //    //获取所有库房
        //    var warehouseobj = _warehouseRepository.QueryIsEntityWhere(x => x.Id == wid && x.Status == 1);
        //    if (warehouseobj == null)
        //    {
        //        message = "库房不存在或已被禁用!";
        //        return null;
        //    }

        //    //获取所有巷道
        //    var routewayQuery = _routewayRepository.GetEntityWhereAll(x => x.WhId == wid && x.Status == 1);
        //    if (routewayQuery == null)
        //    {
        //        message = "无可用巷道!";
        //        return null;
        //    }
        //    List<long> enabledRoutewayIds = routewayQuery.Select(t => t.Id).ToList();//只取巷道id
        //    // 获取所有货架
        //    var shelves = _shelfRepository.GetEntityWhereAll(x => x.WhId == wid && x.AreaId == areaobj.Id && x.Status == 1 && enabledRoutewayIds.Contains((long)x.RoutewayId));
        //    if (shelves == null)
        //    {
        //        message = "无可用货架!";
        //        return null;
        //    }
        //    List<long> enabledShelves = shelves.Select(t => t.Id).ToList();//只取货架id
        //    //获取所有可用仓位
        //    var cellQuery = _cellRepository
        //        .GetEntityWhereAll(x => x.AreaCode == acode
        //                                && x.Status == 1
        //                                && x.FullStatus == 0
        //                                && x.IsLock == false
        //                                && enabledRoutewayIds.Contains((long)x.RoutewayId)
        //                                && enabledShelves.Contains((long)x.ShelfId)).ToList();
        //    if (cellQuery == null)
        //    {
        //        message = "无可用仓位!";
        //        return null;
        //    }
        //    cellobj = cellQuery.Where(x => x.IsMaxDepth == true).OrderByDescending(c => c.DepthIndex)
        //                        .ThenBy(c => c.LayerNo)
        //                        .ThenBy(c => c.ColumnNo)
        //                        .ThenBy(c => c.LineNo)
        //                        .FirstOrDefault();
        //    if (cellobj != null)
        //    {
        //        return cellobj;
        //    }
        //    else
        //    {
        //        cellobj = cellQuery.Where(x => x.IsMaxDepth == false).OrderByDescending(c => c.DepthIndex)
        //                      .ThenBy(c => c.LayerNo)
        //                      .ThenBy(c => c.ColumnNo)
        //                      .ThenBy(c => c.LineNo)
        //                      .FirstOrDefault();
        //        if (cellobj != null)
        //        {
        //            return cellobj;
        //        }
        //    }
        //    if (cellobj == null)
        //        message = "无可用仓位!";
        //    return null;
        //}
        //#endregion
        #endregion

        #region 最新的
        public bool StartShippingOrderDetail(List<SubmitOutListDTO> m, out string message)
        {
            message = string.Empty;
            try
            {
                bool result = false;
                bool tresult = false;
                //是否执行出库----避免一个托盘多种物料重复发送请求
                bool isout = false;
                //是否需要移库----如果出库的是浅货位或者深货位但浅货位没有货的不需要移库
                bool istran = false;
                //是否移库成功
                bool isoktran = false;
                //是否出库成功
                bool isokout = false;
                //要移库的托盘
                string tpalletbarcode = "";
                //要移库的原仓位
                string tlocationcode = "";
                //移动后的仓位
                string ttlocationcode = "";
                //是否为空托
                bool Kpallent = false;
                //是否缠膜
                int Capsule = 0;
              
                Dictionary<string, int> skeyValuePairs = new Dictionary<string, int>();
                var materpacklist = _materialPackageRepository.GetEntityAlls().ToList();
                foreach (var item in m)
                {
                    _unitOfWork.BeginTransaction();
                    isout = false;
                    istran = false;
                    isoktran = false;
                    isokout = false;
                    tpalletbarcode = string.Empty;
                    tlocationcode = string.Empty;
                    ttlocationcode = string.Empty;
                    //物料id
                    long materid = 0;
                    //托盘条码
                    string pacode = item.PalletBarcode;
                    int? billtype;
                    var lockobj = _lockCellRepository.QueryEntityById(item.OrderDetId);
                    if (lockobj.MaterialName == "空托盘")
                    {
                        Kpallent = true;
                    }
                    if (item.Capsule != null)
                    {
                        Capsule = item.Capsule;
                    }
                    if (lockobj == null)
                    {
                        message = "未查询到出库单详情";
                        _unitOfWork.RollbackChanges();
                        return false;
                    }
                    // 出库单数量修改 状态修改
                    if (lockobj.OrderDetailId == null)
                    {
                        message = "出库单信息有误！";
                        _unitOfWork.RollbackChanges();
                        return false;
                    }
                    if (lockobj.Status == 3)
                    {
                        message = $"{lockobj.OrdeSn}正在作业中！";
                        _unitOfWork.RollbackChanges();
                        return false;
                    }
                    if (lockobj.Status == 4)
                    {
                        message = $"{lockobj.OrdeSn}已完成！";
                        _unitOfWork.RollbackChanges();
                        return false;
                    }
                    var materpackobj = materpacklist.FirstOrDefault(x => x.MaterialId == lockobj.MaterialId);
                    lockobj.Status = 3;
                    var shippingOrderDetail = _shippingOrderDetailRepository.QueryEntityById((long)lockobj.OrderDetailId);
                    if (shippingOrderDetail == null)
                    {
                        message = "获取出库单信息失败！";
                        _unitOfWork.RollbackChanges();
                        return false;
                    }
                    if (shippingOrderDetail.Status == 4)
                    {
                        message = "当前出库单已完成！";
                        _unitOfWork.RollbackChanges();
                        return false;
                    }
                    if (shippingOrderDetail.IsSuspend == true)
                    {
                        message = "挂起任务无法执行！";
                        _unitOfWork.RollbackChanges();
                        return false;
                    }
                    billtype = shippingOrderDetail.BillType;
                    shippingOrderDetail.Status = 3;
                    materid = lockobj.MaterialId == null ? 0 : Convert.ToInt64(lockobj.MaterialId);
                    var cellobj = _cellRepository.QueryEntityWhere(x => x.Code == lockobj.CellCode && x.AreaCode== shippingOrderDetail.AreaCode);
                    if (cellobj == null)
                    {
                        message = "未查询到仓位" + lockobj.CellCode;
                        _unitOfWork.RollbackChanges();
                        return false;
                    }
                    if (cellobj.Status != 1 )
                    {
                        if(cellobj.Code != "Cell:2_1_1_1_1")
                        {
                            message = "当前仓位已被禁用！";
                            _unitOfWork.RollbackChanges();
                            return false;
                        }
                      
                    }
                    if (cellobj.RoutewayId == null)
                    {
                        message = "找不到该仓位所属的巷道！";
                        _unitOfWork.RollbackChanges();
                        return false;
                    }
                    var rouwatobj = _routewayRepository.QueryEntityById((long)cellobj.RoutewayId);
                    if (rouwatobj != null && rouwatobj.Status != 1)
                    {
                        message = "当前巷道已被禁用！";
                        _unitOfWork.RollbackChanges();
                        return false;
                    }
                    //获取所有库区
                    var areaobj = _areaRepository.QueryIsEntityWhere(x => x.Code == cellobj.AreaCode && x.Status == 1);
                    if (areaobj == null || areaobj.WhId == null)
                    {
                        message = "库区不存在或已被禁用!";
                        _unitOfWork.RollbackChanges();
                        return false;
                    }
                    long? wid = areaobj.WhId;
                    //获取所有库房
                    var warehouseobj = _warehouseRepository.QueryIsEntityWhere(x => x.Id == wid && x.Status == 1);
                    if (warehouseobj == null)
                    {
                        message = "库房不存在或已被禁用!";
                        _unitOfWork.RollbackChanges();
                        return false;
                    }
                    //获取所有货架
                    var shelves = _shelfRepository.GetEntityWhereAll(x => x.WhId == wid && x.AreaId == areaobj.Id && x.Status == 1 && x.RoutewayId == cellobj.RoutewayId);
                    if (!shelves.Any())
                    {
                        message = "无可用货架!";
                        _unitOfWork.RollbackChanges();
                        return false;
                    }
                    List<long> enabledShelves = shelves.Select(t => t.Id).ToList();//只取货架id
                    if (!enabledShelves.Contains(cellobj.ShelfId ?? 0))
                    {
                        message = "货架已被禁用！";
                        _unitOfWork.RollbackChanges();
                        return false;
                    }
                    long? invid = lockobj.InventoryId;
                    if (invid == null)
                    {
                        message = "获取库存id有误！";
                        _unitOfWork.RollbackChanges();
                        return false;
                    }
                    Inventory? inventoryModel = _inventoryRepository.QueryEntityById((long)invid);
                    //状态修改出库在途         
                    if (inventoryModel == null)
                    {
                        message = "获取库存信息失败！";
                        _unitOfWork.RollbackChanges();
                        return false;
                    }
                    if (materpackobj != null && materpackobj.ConversionFactor > 0 && inventoryModel.AreaCode.Contains('P'))
                        //item.Qty = (decimal)(item.Qty * materpackobj.ConversionFactor);
                    if (inventoryModel.AvailableQty < item.Qty)
                    {
                        message = "库存数量不足！";
                        _unitOfWork.RollbackChanges();
                        return false;
                    }
                    inventoryModel.Status = 4;
                    #region 如果浅深位有货物产生移库操作
                    if (inventoryModel.AreaCode.Contains('L'))
                    {
                        //排
                        // string rows = inventoryModel.LocationCode.Substring(7, 1);
                        string[] parts12 = inventoryModel.LocationCode.Split('_');
                        string rows = parts12[1];
                        if (string.IsNullOrEmpty(rows))
                        {
                            message = "获取仓位排失败！";
                            return false;
                        }
                        if (rows == "1")
                        {
                            string[] parts = inventoryModel.LocationCode.Substring(5).Split(separator: '_');
                            int rou = Convert.ToInt32(parts[0]); // 巷道是第一个数字
                            int row = Convert.ToInt32(parts[1]);    // 排是第二个数字
                            int col = Convert.ToInt32(parts[2]);    // 列是第三个数字
                            int lev = Convert.ToInt32(parts[3]);  // 层是第
                            string modifiedcellcode = $"Cell:{rou}_2_{col}_{lev}_1";
                            var inventorycell = _inventoryRepository.QueryEntityWhere(x => x.LocationCode == modifiedcellcode);
                            if (inventorycell != null && inventorycell.Status == 1 && !skeyValuePairs.ContainsKey(pacode))
                            {
                                tpalletbarcode = inventorycell.PalletBarcode;
                                tlocationcode = inventorycell.LocationCode;
                                istran = true;
                                tresult = ShippingTransferBinInventory(inventoryModel.LocationCode, inventorycell.LocationCode, inventorycell.AreaCode, inventorycell.RoutewayId, inventorycell.PalletBarcode, out message);
                                if (!tresult)
                                {
                                    _unitOfWork.RollbackChanges();
                                    return false;
                                }
                            }
                            else if (inventorycell != null && inventorycell.Status == 2 && !skeyValuePairs.ContainsKey(pacode))
                            {
                                message = $"浅货位{modifiedcellcode}有任务正在作业中，稍后再试！";
                                _unitOfWork.RollbackChanges();
                                return false;
                            }

                        }
                        else if (rows == "5")
                        {
                            string[] parts = inventoryModel.LocationCode.Substring(5).Split(separator: '_');
                            int rou = Convert.ToInt32(parts[0]); // 巷道是第一个数字
                            int row = Convert.ToInt32(parts[1]);    // 排是第二个数字
                            int col = Convert.ToInt32(parts[2]);    // 列是第三个数字
                            int lev = Convert.ToInt32(parts[3]);  // 层是第
                            string modifiedcellcode = $"Cell:{rou}_4_{col}_{lev}_1";
                            var inventorycell = _inventoryRepository.QueryEntityWhere(x => x.LocationCode == modifiedcellcode);
                            if (inventorycell != null && inventorycell.Status == 1 && !skeyValuePairs.ContainsKey(pacode))
                            {
                                tpalletbarcode = inventorycell.PalletBarcode;
                                tlocationcode = inventorycell.LocationCode;
                                istran = true;
                                tresult = ShippingTransferBinInventory(inventoryModel.LocationCode, inventorycell.LocationCode, inventorycell.AreaCode, inventorycell.RoutewayId, inventorycell.PalletBarcode, out message);
                                if (!tresult)
                                {
                                    _unitOfWork.RollbackChanges();
                                    return false;
                                }
                            }
                            else if (inventorycell != null && inventorycell.Status == 2 && !skeyValuePairs.ContainsKey(pacode))
                            {
                                message = $"浅货位{modifiedcellcode}有任务正在作业中，稍后再试！";
                                _unitOfWork.RollbackChanges();
                                return false;
                            }
                        }
                        else if (rows == "6")
                        {
                            string[] parts = inventoryModel.LocationCode.Substring(5).Split(separator: '_');
                            int rou = Convert.ToInt32(parts[0]); // 巷道是第一个数字
                            int row = Convert.ToInt32(parts[1]);    // 排是第二个数字
                            int col = Convert.ToInt32(parts[2]);    // 列是第三个数字
                            int lev = Convert.ToInt32(parts[3]);  // 层是第
                            string modifiedcellcode = $"Cell:{rou}_7_{col}_{lev}_1";
                            var inventorycell = _inventoryRepository.QueryEntityWhere(x => x.LocationCode == modifiedcellcode);
                            if (inventorycell != null && inventorycell.Status == 1 && !skeyValuePairs.ContainsKey(pacode))
                            {
                                tpalletbarcode = inventorycell.PalletBarcode;
                                tlocationcode = inventorycell.LocationCode;
                                istran = true;
                                tresult = ShippingTransferBinInventory(inventoryModel.LocationCode, inventorycell.LocationCode, inventorycell.AreaCode, inventorycell.RoutewayId, inventorycell.PalletBarcode, out message);
                                if (!tresult)
                                {
                                    _unitOfWork.RollbackChanges();
                                    return false;
                                }
                            }
                            else if (inventorycell != null && inventorycell.Status == 2 && !skeyValuePairs.ContainsKey(pacode))
                            {
                                message = $"浅货位{modifiedcellcode}有任务正在作业中，稍后再试！";
                                _unitOfWork.RollbackChanges();
                                return false;
                            }
                        }
                        else if (rows == "10")
                        {
                            string[] parts = inventoryModel.LocationCode.Substring(5).Split(separator: '_');
                            int rou = Convert.ToInt32(parts[0]); // 巷道是第一个数字
                            int row = Convert.ToInt32(parts[1]);    // 排是第二个数字
                            int col = Convert.ToInt32(parts[2]);    // 列是第三个数字
                            int lev = Convert.ToInt32(parts[3]);  // 层是第
                            string modifiedcellcode = $"Cell:{rou}_9_{col}_{lev}_1";
                            var inventorycell = _inventoryRepository.QueryEntityWhere(x => x.LocationCode == modifiedcellcode);
                            if (inventorycell != null && inventorycell.Status == 1 && !skeyValuePairs.ContainsKey(pacode))
                            {
                                tpalletbarcode = inventorycell.PalletBarcode;
                                tlocationcode = inventorycell.LocationCode;
                                istran = true;
                                tresult = ShippingTransferBinInventory(inventoryModel.LocationCode, inventorycell.LocationCode, inventorycell.AreaCode, inventorycell.RoutewayId, inventorycell.PalletBarcode, out message);
                                if (!tresult)
                                {
                                    _unitOfWork.RollbackChanges();
                                    return false;
                                }
                            }
                            else if (inventorycell != null && inventorycell.Status == 2 && !skeyValuePairs.ContainsKey(pacode))
                            {
                                message = $"浅货位{modifiedcellcode}有任务正在作业中，稍后再试！";
                                _unitOfWork.RollbackChanges();
                                return false;
                            }
                        }
                        else if (rows == "11")
                        {
                            string[] parts = inventoryModel.LocationCode.Substring(5).Split(separator: '_');
                            int rou = Convert.ToInt32(parts[0]); // 巷道是第一个数字
                            int row = Convert.ToInt32(parts[1]);    // 排是第二个数字
                            int col = Convert.ToInt32(parts[2]);    // 列是第三个数字
                            int lev = Convert.ToInt32(parts[3]);  // 层是第
                            string modifiedcellcode = $"Cell:{rou}_12_{col}_{lev}_1";
                            var inventorycell = _inventoryRepository.QueryEntityWhere(x => x.LocationCode == modifiedcellcode);
                            if (inventorycell != null && inventorycell.Status == 1 && !skeyValuePairs.ContainsKey(pacode))
                            {
                                tpalletbarcode = inventorycell.PalletBarcode;
                                tlocationcode = inventorycell.LocationCode;
                                istran = true;
                                tresult = ShippingTransferBinInventory(inventoryModel.LocationCode, inventorycell.LocationCode, inventorycell.AreaCode, inventorycell.RoutewayId, inventorycell.PalletBarcode, out message);
                                if (!tresult)
                                {
                                    _unitOfWork.RollbackChanges();
                                    return false;
                                }
                            }
                            else if (inventorycell != null && inventorycell.Status == 2 && !skeyValuePairs.ContainsKey(pacode))
                            {
                                message = $"浅货位{modifiedcellcode}有任务正在作业中，稍后再试！";
                                _unitOfWork.RollbackChanges();
                                return false;
                            }
                        }
                        else if (rows == "15")
                        {
                            string[] parts = inventoryModel.LocationCode.Substring(5).Split(separator: '_');
                            int rou = Convert.ToInt32(parts[0]); // 巷道是第一个数字
                            int row = Convert.ToInt32(parts[1]);    // 排是第二个数字
                            int col = Convert.ToInt32(parts[2]);    // 列是第三个数字
                            int lev = Convert.ToInt32(parts[3]);  // 层是第
                            string modifiedcellcode = $"Cell:{rou}_14_{col}_{lev}_1";
                            var inventorycell = _inventoryRepository.QueryEntityWhere(x => x.LocationCode == modifiedcellcode);
                            if (inventorycell != null && inventorycell.Status == 1 && !skeyValuePairs.ContainsKey(pacode))
                            {
                                tpalletbarcode = inventorycell.PalletBarcode;
                                tlocationcode = inventorycell.LocationCode;
                                istran = true;
                                tresult = ShippingTransferBinInventory(inventoryModel.LocationCode, inventorycell.LocationCode, inventorycell.AreaCode, inventorycell.RoutewayId, inventorycell.PalletBarcode, out message);
                                if (!tresult)
                                {
                                    _unitOfWork.RollbackChanges();
                                    return false;
                                }
                            }
                            else if (inventorycell != null && inventorycell.Status == 2 && !skeyValuePairs.ContainsKey(pacode))
                            {
                                message = $"浅货位{modifiedcellcode}有任务正在作业中，稍后再试！";
                                _unitOfWork.RollbackChanges();
                                return false;
                            }
                        }
                    }
                    #endregion
                    var inventorylist = _inventoryRepository.GetEntityWhereAll(x => x.PalletBarcode == pacode && x.Status == 1&& x.Id== lockobj.InventoryId);
                    if (inventorylist.Any())
                    {
                        foreach (var item2 in inventorylist)
                        {
                            item2.IsLock = true;
                            item2.Status = 4;
                            _inventoryRepository.UpdEntity(item2);
                        }
                    }
                    #region 添加指令
                    Instruct inobj = new Instruct();
                    inobj.WarehouseCode = inventoryModel.WarehouseCode;
                    inobj.Status = 2;
                    inobj.FromLocation = item.StationCode;
                    inobj.ToLocation = inventoryModel.LocationCode;
                    inobj.WorkDeviceType = 1;
                    if (billtype == 2)
                        inobj.InstructType = 6;
                    else
                        inobj.InstructType = 2;
                    inobj.Action = 0;
                    inobj.RelatedOrderId = shippingOrderDetail.Id;
                    inobj.ExpectedToLocation = inventoryModel.LocationCode;
                    inobj.InstructIndex = 1;
                    inobj.PalletBarcode = pacode;
                    inobj.ScanedBarcode = pacode;
                    inobj.Priority = 9999;
                    inobj.Qty = item.Qty;
                    inobj.FinishedQty = 0;
                    inobj.BusinessType = (int)EmBusinessType.Out;
                    inobj.RelatedOrderDetailId = lockobj.Id;
                    inobj.CreateUserId = item.NowUserId;
                    inobj.CreateUserName = item.NowUserName;
                    _instructRepository.AddEntity(inobj);
                    #endregion
                    #region 添加下架单
                    string str = DateTime.Now.ToString("yyyyMMddHHmmssfff");
                    string pickCode = "OUT" + str;
                    PickingOrder pickOrder = new PickingOrder();
                    pickOrder.Id = YitIdHelper.NextId();
                    pickOrder.Code = pickCode;
                    pickOrder.WarehouseCode = inventoryModel.WarehouseCode;
                    pickOrder.WarehouseName = inventoryModel.WarehouseName;
                    if (billtype == 2)
                        pickOrder.BillType = 2;
                    else
                        pickOrder.BillType = 1;
                    pickOrder.DescAddress = item.DescAddress;
                    pickOrder.PalletBarcode = pacode;
                    pickOrder.Roadway = cellobj.RoutewayId.ToString();
                    pickOrder.LocationCode = cellobj.Code;
                    pickOrder.LocationDepth = cellobj.DepthIndex;
                    pickOrder.Status = 4;
                    pickOrder.Qty = item.Qty;
                    pickOrder.MaterialId = materid;
                    pickOrder.MaterialCode = lockobj.MaterialCode;
                    pickOrder.MaterialName = lockobj.MaterialName;
                    pickOrder.MaterialKeyId = inventoryModel.MaterialKeyId;
                    pickOrder.BatchNo = inventoryModel.BatchNo;
                    pickOrder.SourceType = 2;
                    pickOrder.RelatedOrderDetailId = item.OrderDetId;
                    pickOrder.CreateDate = DateTime.Now;
                    if (inventoryModel.AreaCode.Contains('L'))
                    {
                        if (!skeyValuePairs.ContainsKey(pacode))
                        {
                            skeyValuePairs.Add(pacode, 1);
                            isout = true;
                        }
                    }
                    _pickingOrderRepository.AddEntity(pickOrder);
                    PickingOrderDetail pickOrderDetail = new PickingOrderDetail();
                    pickOrderDetail.Id = YitIdHelper.NextId();
                    pickOrderDetail.OrderId = pickOrder.Id;
                    pickOrderDetail.PalletBarcode = pacode;
                    pickOrderDetail.MaterialBarcode = lockobj.MaterialCode;
                    _pickingOrderDetailRepository.AddEntity(pickOrderDetail);
                    #endregion
                    result = _unitOfWork.SaveChangesEntity();
                    if (!result)
                    {
                        message = "出库解绑失败！";
                        _unitOfWork.RollbackChanges();
                        return false;
                    }
                    if (cellobj.AreaCode.Contains("P"))
                    {
                        result = StaticFinishShippingOrderDetail(pickCode, out message);
                        if (result)
                        {
                            _unitOfWork.CommitChanges();
                            continue;
                        }
                        else
                        {
                            _unitOfWork.RollbackChanges();
                            return false;
                        }

                    }
                    
                    if (result)
                    {
                       
                        //WMS给WCS下发出,移库任务
                        if (Config.IsDev == false && isout)
                        {

                            if (istran)
                            {
                                var putobj = _putawayOrderRepository.QueryEntityWhere(x => x.PalletBarcode == tpalletbarcode && x.Status == 4 && x.SourceType == 3);
                                if (putobj == null)
                                {
                                    message = "找不到上架单信息！";
                                    _unitOfWork.RollbackChanges();
                                    return false;
                                }
                                var inventory = _inventoryRepository.QueryEntityWhere(d => d.RelatedOrderDetailId == putobj.RelatedOrderDetailId);
                                if (inventory == null)
                                {
                                    message = "找不到上架单关联的库存！";
                                    _unitOfWork.RollbackChanges();
                                    return false;
                                }
                                string[] parts = tlocationcode.Substring(5).Split(separator: '_');
                                string[] toparts = putobj.LocationCode.Substring(5).Split(separator: '_');

                                var endLocation = _cellRepository.QueryEntityWhere(d => d.Code == putobj.LocationCode);


                                //移库
                                //WcsTranTaskDto wcsTaskDto = new WcsTranTaskDto
                                //{
                                //    TaskCode = putobj.Code,
                                //    //FromTunnel = Convert.ToInt32(parts[0]),
                                //    //FromRow = Convert.ToInt32(parts[1]),
                                //    //FromBay = Convert.ToInt32(parts[2]),
                                //    //FromLevel = Convert.ToInt32(parts[3]),
                                //    //ToTunnel = Convert.ToInt32(toparts[0]),
                                //    //ToRow = Convert.ToInt32(toparts[1]),
                                //    //ToBay = Convert.ToInt32(toparts[2]),
                                //    //ToLevel = Convert.ToInt32(toparts[3]),

                                //    PalletCode = putobj.PalletBarcode,
                                //};
                                WcsTaskDto wcsTaskDto = new WcsTaskDto
                                {
                                    TaskCode = putobj.Code,
                                    TaskType = 3,
                                    CellCode = endLocation.Erpcode,
                                    AgvStartCode = "",
                                    //移库为0，缠膜字段
                                    Capsule = 0,
                                    //子托盘码
                                    StockCode = inventory.ParentPalletBarcode,
                                    //托盘码
                                    PalletCode = putobj.PalletBarcode,
                                };
                                var wcsresult = _wcsHttpClient.OutTaskApi(wcsTaskDto);
                                if (wcsresult.Code != EmApiResCode.Success)
                                {
                                    message = wcsresult.ReturnInfo;
                                    result = false;
                                    _unitOfWork.RollbackChanges();
                                    break;
                                }
                                else
                                {
                                    ttlocationcode = putobj.LocationCode;
                                    isoktran = true;
                                    InterfaceLog interfaceLog = new InterfaceLog();
                                    interfaceLog.Name = "SendTask";
                                    interfaceLog.Url = "wcs/ExternalApi/SendTask";
                                    interfaceLog.CallWay = 2;
                                    interfaceLog.CallWayStr = "POST";
                                    interfaceLog.InParam = JsonConvert.SerializeObject(m);
                                    interfaceLog.OutParam = wcsresult.ReturnInfo + $"(移库)托盘{tpalletbarcode}原仓位{tlocationcode}已被移动至{ttlocationcode}";
                                    interfaceLog.ExecDate = DateTime.Now;
                                    interfaceLog.FinishedDate = DateTime.Now;
                                    interfaceLog.Status = 1;
                                    _interfaceLogRepository.AddEntity(interfaceLog);
                                    _unitOfWork.SaveChangesEntity();
                                }
                            }
                            if (!Kpallent)
                            {
                                //出库
                                string[] outparts = pickOrder.LocationCode.Substring(5).Split(separator: '_');
                                WcsTaskDto wcsTaskDto2 = new WcsTaskDto
                                {
                                    //下架单
                                    TaskCode = pickOrder.Code,
                                    TaskType = 2,
                                    CellCode = cellobj.Erpcode,
                                    AgvStartCode = inventoryModel.AgvStartCode,
                                    //出库的时候判断是否库存是否缠膜，
                                    Capsule = Capsule,
                                    //Tunnel = Convert.ToInt32(outparts[0]),
                                    //Row = Convert.ToInt32(outparts[1]),
                                    //Bay = Convert.ToInt32(outparts[2]),
                                    //Level = Convert.ToInt32(outparts[3]),
                                    //子托盘码
                                    StockCode = inventoryModel.ParentPalletBarcode,
                                    //托盘码
                                    PalletCode = inventoryModel.PalletBarcode,
                                    //Qty = pickOrder.Qty
                                };
                                WcsTaskResultDto? wcsresult2 = _wcsHttpClient.OutTaskApi(wcsTaskDto2);
                                if (wcsresult2.Code != EmApiResCode.Success)
                                {
                                    message = wcsresult2.Msg;
                                    result = false;
                                    _unitOfWork.RollbackChanges();
                                    break;
                                }
                                else
                                {
                                    isokout = true;
                                    InterfaceLog interfaceLog = new InterfaceLog();
                                    interfaceLog.Name = "SendTask";
                                    interfaceLog.Url = "wcs/ExternalApi/SendTask";
                                    interfaceLog.CallWay = 2;
                                    interfaceLog.CallWayStr = "POST";
                                    interfaceLog.InParam = JsonConvert.SerializeObject(m);
                                    interfaceLog.OutParam = wcsresult2.Msg + $"(出库)托盘{inventoryModel.PalletBarcode} 仓位{inventoryModel.LocationCode}";
                                    interfaceLog.ExecDate = DateTime.Now;
                                    interfaceLog.FinishedDate = DateTime.Now;
                                    interfaceLog.Status = 1;
                                    _interfaceLogRepository.AddEntity(interfaceLog);
                                    _unitOfWork.SaveChangesEntity();
                                }
                            }
                            
                        }
                        message = "操作成功！";
                        _unitOfWork.CommitChanges();
                    }
                    else
                    {
                        _unitOfWork.RollbackChanges();
                        return false;
                    }
                }
                if (!result)
                {
                    InterfaceLog interfaceLog = new InterfaceLog();
                    interfaceLog.CallWay = 2;
                    interfaceLog.CallWayStr = "POST";
                    interfaceLog.InParam = JsonConvert.SerializeObject(m);
                    interfaceLog.ExecDate = DateTime.Now;
                    interfaceLog.FinishedDate = DateTime.Now;
                    if (istran && !isoktran)
                    {
                        interfaceLog.Name = "SendMoveTask";
                        interfaceLog.Url = "wcs/ExternalApi/SendMoveTask";
                        interfaceLog.Status = 3;
                        interfaceLog.OutParam = $"移库失败！托盘号{tpalletbarcode} 仓位{tlocationcode}";
                        interfaceLog.ErrorMsg = message;
                    }
                    else if (isoktran && !isokout)
                    {
                        interfaceLog.Name = "LpStationStatus";
                        interfaceLog.Url = "wcs/ExternalApi/LpStationStatus";
                        interfaceLog.Status = 3;
                        interfaceLog.OutParam = $"移库成功！但出库未成功。托盘{tpalletbarcode}原仓位{tlocationcode}已被移动至{ttlocationcode}";
                        interfaceLog.ErrorMsg = message;
                    }
                    else
                    {
                        interfaceLog.Name = "LpStationStatus";
                        interfaceLog.Url = "wcs/ExternalApi/LpStationStatus";
                        interfaceLog.Status = 3;
                        interfaceLog.OutParam = $"出库未成功！";
                        interfaceLog.ErrorMsg = message;
                    }
                    _interfaceLogRepository.AddEntity(interfaceLog);
                    _unitOfWork.SaveChangesEntity();
                    return false;
                }
                else
                {
                    return true;
                }
            }
            catch (Exception)
            {
                _unitOfWork.RollbackChanges();
                throw;
            }

        }
        #region 出库产生移库逻辑处理
        private bool ShippingTransferBinInventory(string fromcellcode, string trancellcode, string acode, long? rouid, string pacode, out string message)
        {
            message = string.Empty;
            #region 修改库存状态
            var toCell = GetCellCode(acode, rouid, out message);
            if (toCell == null)
            {
                return false;
            }
            else
            {
                toCell.FullStatus = 1;
                toCell.IsLock = true;
                toCell.BusinessType = 1;
                toCell.ModifyDate = DateTime.Now;
                _cellRepository.UpdEntity(toCell);
            }
            bool isshipplost = false;
            var slocklist = _lockCellRepository.GetEntityWhereAll(x => x.CellCode == trancellcode && x.Status == 0).ToList();
            foreach (var item2 in slocklist)
            {
                //标记状态列
                item2.CellId = toCell.Id;
                item2.CellCode = toCell.Code;
                item2.CellName = toCell.Name;
                item2.Status = 3;
                item2.CellDepthIndex = toCell.DepthIndex;
                isshipplost = true;
                _lockCellRepository.UpdEntity(item2);
            }
            var tinventorylist = _inventoryRepository.GetEntityWhereAll(it => it.LocationCode == trancellcode).ToList();
            foreach (var inventory in tinventorylist)
            {
                inventory.LocationId = toCell.Id;
                inventory.LocationName = toCell.Name;
                inventory.LocationCode = toCell.Code;
                inventory.LocationDepth = toCell.DepthIndex;
                inventory.LocationLineNo = toCell.LineNo;
                inventory.LocationLayerNo = toCell.LayerNo;
                inventory.LocationColumnNo = toCell.ColumnNo;
                inventory.LocationDistanceValue = Convert.ToInt32(toCell.IsMaxDepth);
                inventory.Status = 2;
                inventory.LocationHeightType = toCell.HeightType;
                inventory.IsLock = true;
                inventory.RoutewayId = toCell.RoutewayId;
                inventory.ErplocationCode = toCell.Erpcode;
                if (isshipplost)
                    inventory.Remark = "系统移库";
                _inventoryRepository.UpdEntity(inventory);
                #region 关联的入库单做处理
                if (inventory.RelatedOrderDetailId == null)
                {
                    message = "关联的入库单id有误！";
                    return false;
                }
                var revingobj = _receivingOrderDetailRepository.QueryEntityById((long)inventory.RelatedOrderDetailId);
                if (revingobj == null)
                {
                    message = "入库单明细不存在或已被删除";
                    return false;
                }
                #region 指令管理
                Instruct instruct = null;
                instruct = new Instruct
                {
                    WarehouseCode = toCell.WhCode,
                    Status = 2,
                    FromLocation = trancellcode,
                    ToLocation = toCell.Code,
                    StackingStorageId = 0,
                    WorkDeviceType = 1,
                    InstructType = 3,
                    Action = 0,
                    RelatedOrderId = revingobj.Id,
                    RelatedOrderDetailId = 0,
                    DeviceCode = "",
                    ExpectedToLocation = toCell.Code,
                    InstructIndex = 1,
                    PalletBarcode = pacode,
                    ScanedBarcode = pacode,
                    Priority = 9999,
                    Qty = inventory.AvailableQty == null ? 0 : (decimal)inventory.AvailableQty,
                    FinishedQty = 0,
                    CreateDate = DateTime.Now,
                    BusinessType = (int)EmBusinessType.Move,
                    BillType = (int)revingobj.BillType.GetValueOrDefault(),
                };
                _instructRepository.AddEntity(instruct);
                #endregion
                #endregion

                #region 上架单
                string tstr = DateTime.Now.ToString("yyyyMMddHHmmssfff");
                string traawayCode = "TRA" + tstr;
                PutawayOrder putawayOrder = new PutawayOrder();
                putawayOrder.Id = YitIdHelper.NextId();
                putawayOrder.Code = traawayCode;
                putawayOrder.RelatedOrderDetailId = tinventorylist.First().RelatedOrderDetailId;
                putawayOrder.StackingStorageId = 0;
                putawayOrder.PalletBarcode = tinventorylist.First().PalletBarcode;
                putawayOrder.LocationCode = toCell.Code;
                putawayOrder.LocationDepth = toCell.DepthIndex == 0 ? null : toCell.DepthIndex;
                putawayOrder.Status = 4;
                putawayOrder.Qty = tinventorylist.First().AvailableQty;
                putawayOrder.CreateDate = DateTime.Now;
                putawayOrder.MaterialId = tinventorylist.First().MaterialId;
                putawayOrder.MaterialCode = tinventorylist.First().MaterialCode;
                putawayOrder.MaterialName = tinventorylist.First().MaterialName;
                putawayOrder.MaterialKeyId = tinventorylist.First().MaterialKeyId;
                putawayOrder.BatchNo = tinventorylist.First().BatchNo;
                putawayOrder.CreateUserId = 0;
                putawayOrder.CreateUserName = "系统";
                putawayOrder.SourceType = 3;
                putawayOrder.SiteCode = "";
                _putawayOrderRepository.AddEntity(putawayOrder);
            }
            #endregion
            var pallobj = _palletRepository.QueryEntityWhere(x => x.LocationCode == trancellcode);
            if (pallobj != null)
            {
                pallobj.LocationName = toCell.Name;
                pallobj.LocationCode = toCell.Code;
            }

            #endregion
            return _unitOfWork.SaveChangesEntity();
        }

        private DFGK_WMS.Model.Models.Cell? GetCellCode(string acode, long? rouid, out string message)
        {
            message = string.Empty;
            if (string.IsNullOrEmpty(acode))
            {
                message = "库区编码有误！";
                return null;
            }
            //获取所有库区
            var areaobj = _areaRepository.QueryIsEntityWhere(x => x.Code == acode && x.Status == 1);
            if (areaobj == null || areaobj.WhId == null)
            {
                message = "库区不存在或已被禁用!";
                return null;
            }
            long? wid = areaobj.WhId;
            //获取所有库房
            var warehouseobj = _warehouseRepository.QueryIsEntityWhere(x => x.Id == wid && x.Status == 1);
            if (warehouseobj == null)
            {
                message = "库房不存在或已被禁用!";
                return null;
            }

            //获取所有巷道
            var routewayQuery = _routewayRepository.GetEntityWhereAll(x => x.WhId == wid && x.Status == 1);
            if (!routewayQuery.Any())
            {
                message = "无可用巷道!";
                return null;
            }
            var allroutewayid = routewayQuery.Select(x => x.Id).ToList();
            allroutewayid = allroutewayid.OrderByDescending(x => x).ToList();
            foreach (var rid in allroutewayid)
            {
                //获取所有货架
                var shelves = _shelfRepository.GetEntityWhereAll(x => x.WhId == wid && x.AreaId == areaobj.Id && x.Status == 1 && x.RoutewayId == rid);
                if (!shelves.Any())
                {
                    message = "无可用货架!";
                    continue;
                }
                List<long> enabledShelves = shelves.Select(t => t.Id).ToList();//只取货架id
                var allcell = _cellRepository.GetEntityWhereAll(x => enabledShelves.Contains(x.ShelfId ?? 0) && x.Status == 1 && x.FullStatus == 0 && x.BusinessType == 0 && x.IsLock == false).ToList();
                int ycount = 0;
                int ncount = 0;
                long routewayid = 0;
                //默认找最深的
                bool ismaxdepth = true;
                ycount = allcell.Where(x => x.RoutewayId == rid && x.IsMaxDepth == true).Count();
                ncount = allcell.Where(x => x.RoutewayId == rid && x.IsMaxDepth == false).Count();
                //深的2个 浅的是1个
                if (ycount < 1)
                {
                    if (ncount < 1)
                        continue;
                    ismaxdepth = false;
                    routewayid = rid;
                }
                else
                {
                    routewayid = rid;
                }
                if (routewayid == 0)
                {
                    message = "无可用仓位！";
                    continue;
                }
                var cellQuery = _cellRepository.GetEntityWhereAll(x => x.AreaCode == acode && x.Status == 1 && x.FullStatus == 0 && x.IsLock == false && x.BusinessType == 0 && enabledShelves.Contains(x.ShelfId ?? 0));
                if (!cellQuery.Any())
                {
                    message = "无可用仓位!";
                    continue;
                }
                if (ismaxdepth)
                {
                    var cellsIsMaxDepths = cellQuery.Where(x => x.IsMaxDepth == true).OrderByDescending(c => c.DepthIndex)
                                  .ThenBy(c => c.LayerNo)
                                  .ThenBy(c => c.ColumnNo)
                                  .ThenBy(c => c.LineNo).ToList();
                    foreach (var item in cellsIsMaxDepths)
                    {
                        //排
                        string rows = item.Code.Substring(7, 1);
                        if (string.IsNullOrEmpty(rows))
                        {
                            message = "获取仓位排失败！";
                            continue;
                        }
                        if (rows == "1")
                        {
                            string[] parts = item.Code.Substring(5).Split(separator: '_');
                            int rou = Convert.ToInt32(parts[0]); // 巷道是第一个数字
                            int row = Convert.ToInt32(parts[1]);    // 排是第二个数字
                            int col = Convert.ToInt32(parts[2]);    // 列是第三个数字
                            int lev = Convert.ToInt32(parts[3]);  // 层是第
                            string modifiedcellcode = $"Cell:{rou}_2_{col}_{lev}_1";
                            var inventorycell = _inventoryRepository.QueryEntityWhere(x => x.LocationCode == modifiedcellcode);
                            if (inventorycell != null)
                                continue;
                            else
                            {
                                message = item.Code;
                                return item;
                            }
                        }
                        else if (rows == "4")
                        {
                            string[] parts = item.Code.Substring(5).Split(separator: '_');
                            int rou = Convert.ToInt32(parts[0]); // 巷道是第一个数字
                            int row = Convert.ToInt32(parts[1]);    // 排是第二个数字
                            int col = Convert.ToInt32(parts[2]);    // 列是第三个数字
                            int lev = Convert.ToInt32(parts[3]);  // 层是第
                            string modifiedcellcode = $"Cell:{rou}_3_{col}_{lev}_1";
                            var inventorycell = _inventoryRepository.QueryEntityWhere(x => x.LocationCode == modifiedcellcode);
                            if (inventorycell != null)
                                continue;
                            else
                            {
                                message = item.Code;
                                return item;
                            }
                        }
                    }
                }
                var cellsIsMaxDepths2 = cellQuery.Where(x => x.IsMaxDepth == false).OrderByDescending(c => c.DepthIndex)
                             .ThenBy(c => c.LayerNo)
                             .ThenBy(c => c.ColumnNo)
                             .ThenBy(c => c.LineNo).ToList();
                foreach (var item in cellsIsMaxDepths2)
                {
                    //排
                    string rows = item.Code.Substring(7, 1);
                    if (string.IsNullOrEmpty(rows))
                    {
                        message = "获取仓位排失败！";
                        continue;
                    }
                    if (rows == "2")
                    {
                        string[] parts = item.Code.Substring(5).Split(separator: '_');
                        int rou = Convert.ToInt32(parts[0]); // 巷道是第一个数字
                        int row = Convert.ToInt32(parts[1]);    // 排是第二个数字
                        int col = Convert.ToInt32(parts[2]);    // 列是第三个数字
                        int lev = Convert.ToInt32(parts[3]);  // 层是第
                        string modifiedcellcode = $"Cell:{rou}_1_{col}_{lev}_2";
                        var inventorycell = _inventoryRepository.QueryEntityWhere(x => x.LocationCode == modifiedcellcode);
                        if (inventorycell != null && inventorycell.Status == 1)
                        {
                            message = item.Code;
                            return item;
                        }
                        else
                            continue;
                    }
                    else if (rows == "3")
                    {
                        string[] parts = item.Code.Substring(5).Split(separator: '_');
                        int rou = Convert.ToInt32(parts[0]); // 巷道是第一个数字
                        int row = Convert.ToInt32(parts[1]);    // 排是第二个数字
                        int col = Convert.ToInt32(parts[2]);    // 列是第三个数字
                        int lev = Convert.ToInt32(parts[3]);  // 层是第
                        string modifiedcellcode = $"Cell:{rou}_4_{col}_{lev}_2";
                        var inventorycell = _inventoryRepository.QueryEntityWhere(x => x.LocationCode == modifiedcellcode);
                        if (inventorycell != null && inventorycell.Status == 1)
                        {
                            message = item.Code;
                            return item;
                        }
                        else
                            continue;
                    }
                }
            }
            message = "无可用仓位!";
            return null;
        }
        #endregion
        #endregion

        private bool StaticFinishShippingOrderDetail(string pickcode, out string message)
        {
            message = "";
            bool IsNullPallet = false; 
            int? shippqty = 0;
            bool ispack = true;
            var pickobj = _pickingOrderRepository.QueryEntityWhere(x => x.Code == pickcode && x.SourceType == 2 && x.Status == 4);
            if (pickobj == null)
            {
                message = "找不到下架单！";
                return false;
            }
            
            PackageDetail packageDetail = new PackageDetail();
            var instructlist = _instructRepository.GetEntityWhereAll(x => x.PalletBarcode == pickobj.PalletBarcode && x.Status == 2 && x.InstructType == 2 || (x.PalletBarcode == pickobj.PalletBarcode && x.Status == 2 && x.InstructType == 6)).ToList();
            if (!instructlist.Any())
            {
                message = "未查询到指令！";
                return false;
            }
            var palllist = _palletRepository.GetEntityAll();
            var materpacklist = _materialPackageRepository.GetEntityAll().ToList();
            bool result;
            try
            {

                foreach (var instruct in instructlist)
                {
                    var areaCode = _shippingOrderDetailRepository.QueryEntityWhere(d => d.Id == instruct.RelatedOrderId).AreaCode;
                    var tell = _cellRepository.QueryEntityWhere(x => x.Code == instruct.ExpectedToLocation && x.AreaCode == areaCode);
                    if (tell == null)
                    {
                        message = "未查询到仓位！";
                        _unitOfWork.RollbackChanges();
                        return false;
                    }
                    instruct.Status = 4;
                    instruct.EndTime = DateTime.Now;
                    //出库单id
                    long? shippid = instruct.RelatedOrderId;
                    if (shippid == null)
                    {
                        message = "出库单明细id有误！";
                        _unitOfWork.RollbackChanges();
                        return false;
                    }
                    var shippingOrderDetail = _shippingOrderDetailRepository.QueryEntityById((long)shippid);
                    if (shippingOrderDetail == null)
                    {
                        message = "未查询到单号";
                        return false;
                    }
                    shippingOrderDetail.ShippedQty += instruct.Qty;
                    if (shippingOrderDetail.ShippedQty == shippingOrderDetail.Qty)
                    {
                        shippingOrderDetail.Status = 4;
                        shippingOrderDetail.FinshDate = DateTime.Now;
                    }
                    _shippingOrderDetailRepository.UpdEntity(shippingOrderDetail);
                    if (instruct.RelatedOrderDetailId == null)
                    {
                        message = "出库单明细id有误！";
                        _unitOfWork.RollbackChanges();
                        return false;
                    }
                    var lockobj = _lockCellRepository.QueryEntityById((long)instruct.RelatedOrderDetailId);
                    if (lockobj == null)
                    {
                        message = "未查询到单号" + shippingOrderDetail.OrderSn + "的出库单详情";
                        _unitOfWork.RollbackChanges();
                        return false;
                    }
                    lockobj.InventoryQty -= instruct.Qty;
                    //拿到库存id
                    long? invid = lockobj.InventoryId;
                    if (invid == null)
                    {
                        message = "出库明细中库存id有误！";
                        _unitOfWork.RollbackChanges();
                        return false;
                    }
                    Inventory? inventoryModel = _inventoryRepository.QueryEntityById((long)invid);
                    if (inventoryModel.PalletBarcode == "0")
                    {
                        IsNullPallet = false;
                    }
                    else
                    {
                        IsNullPallet = true;
                    }
                    if (inventoryModel == null)
                    {
                        message = "未查询到库存信息！";
                        _unitOfWork.RollbackChanges();
                        return false;
                    }
                    else
                    {
                        lockobj.Status = 4;
                        lockobj.CachePortCode = "----";
                        lockobj.PackCode = "----";
                        _lockCellRepository.UpdEntity(lockobj);
                    }
                    decimal? startQty = inventoryModel.AvailableQty;
                    decimal? changeQty = instruct.Qty;
                    // 库存数量减去需要出库的数量
                    if (inventoryModel.AvailableQty - instruct.Qty == 0)
                    {
                        _inventoryRepository.DelEntity(inventoryModel);
                      var receivingOrderDetail=  _receivingOrderDetailRepository.QueryEntityWhere(d => d.Id == inventoryModel.RelatedOrderDetailId);
                        var packDetailList = _packageDetailRepository.GetAllEntityList().Where(d => d.RelatedOrderDetailId == receivingOrderDetail.ReceivingBillId).ToList();
                        _packageDetailRepository.DelEntityList(packDetailList);
                        var idobj = _inventoryDetailRepository.QueryEntityWhere(x => x.InventoryId == inventoryModel.Id);
                        if (idobj != null)
                            _inventoryDetailRepository.DelEntity(idobj);

                        result = _unitOfWork.SaveChangesEntity();
                        if (!result)
                        {
                            message = "删除库存信息出错！";
                            _unitOfWork.RollbackChanges();
                            return false;
                        }
                        var pallobj = palllist.FirstOrDefault(x => x.LocationCode == tell.Code && x.LocationName == tell.Name);
                        var invpal = _inventoryRepository.GetEntityWhereAll(x => x.PalletBarcode == instruct.PalletBarcode);
                        if (!invpal.Any())
                        {

                            tell.FullStatus = 0;
                            tell.IsLock = false;
                            tell.BusinessType = 0;
                            tell.ModifyDate = DateTime.Now;
                            tell.Status = 1;
                            _cellRepository.UpdEntity(tell);
                            if (pallobj != null)
                            {
                                pallobj.LocationName = string.Empty;
                                pallobj.LocationCode = string.Empty;
                            }
                        }
                    }
                    else
                    {
                        if (inventoryModel.AreaCode.Contains('P'))
                        {
                            inventoryModel.Status = 1;
                        }
                        else
                        {
                            StackingStorage stackingStorage = new StackingStorage()
                            {
                                AreaCode = inventoryModel.AreaCode,
                                MaterialId = inventoryModel.MaterialId,
                                BatchNo = inventoryModel.BatchNo,
                                YRid = tell.RoutewayId
                            };
                            if (GetCellCode(stackingStorage, out message))
                            {
                                string cellcode = "";
                                cellcode = message;
                                //锁仓位
                                var cell = _cellRepository.QueryEntityWhere(x => x.Code == cellcode);
                                if (cell != null)
                                {
                                    tell.FullStatus = 0;
                                    tell.IsLock = false;
                                    tell.BusinessType = 0;
                                    tell.ModifyDate = DateTime.Now;
                                    _cellRepository.UpdEntity(tell);
                                    cell.BusinessType = 1;
                                    cell.IsLock = true;
                                    cell.FullStatus = 1;
                                    _cellRepository.UpdEntity(cell);
                                    inventoryModel.LocationId = cell.Id;
                                    inventoryModel.LocationCode = cell.Code;
                                    inventoryModel.LocationName = cell.Name;
                                    inventoryModel.LocationLineNo = cell.LineNo;
                                    inventoryModel.RoutewayId = cell.RoutewayId;
                                    inventoryModel.LocationColumnNo = cell.ColumnNo;
                                    inventoryModel.LocationLayerNo = cell.LayerNo;
                                    inventoryModel.LocationDepth = cell.DepthIndex;
                                    inventoryModel.LocationDistanceValue = Convert.ToInt32(cell.IsMaxDepth);
                                    _inventoryRepository.UpdEntity(inventoryModel);
                                    var pallobj = palllist.FirstOrDefault(x => x.LocationCode == tell.Code && x.LocationName == tell.Name);
                                    if (pallobj != null)
                                    {
                                        pallobj.LocationName = cell.Name;
                                        pallobj.LocationCode = cell.Code;
                                        _palletRepository.UpdEntity(pallobj);
                                    }
                                    Instruct instruct2 = new Instruct
                                    {
                                        Status = 2,
                                        WarehouseCode = inventoryModel.WarehouseCode,
                                        ToLocation = inventoryModel.LocationCode,
                                        WorkDeviceType = 1,
                                        InstructType = 7,
                                        Action = 0,
                                        RelatedOrderId = inventoryModel.RelatedOrderDetailId,
                                        ExpectedToLocation = inventoryModel.LocationCode,
                                        InstructIndex = 1,
                                        PalletBarcode = inventoryModel.PalletBarcode,
                                        Priority = 9999,
                                        Qty = (decimal)inventoryModel.AvailableQty - instruct.Qty,
                                        BusinessType = (int)EmBusinessType.In,
                                    };
                                    _instructRepository.AddEntity(instruct2);
                                    string str = DateTime.Now.ToString("yyyyMMddHHmmssfff");
                                    string putawayCode = "SRT" + str;
                                    PutawayOrder putawayOrder = new PutawayOrder();
                                    putawayOrder.Id = YitIdHelper.NextId();
                                    putawayOrder.Code = putawayCode;
                                    putawayOrder.BillType = 2;
                                    putawayOrder.RelatedOrderDetailId = inventoryModel.RelatedOrderDetailId;
                                    putawayOrder.PalletBarcode = inventoryModel.PalletBarcode;
                                    putawayOrder.LocationCode = inventoryModel.LocationCode;
                                    putawayOrder.LocationDepth = inventoryModel.LocationDepth == 0 ? null : inventoryModel.LocationDepth;
                                    putawayOrder.Status = 4;
                                    putawayOrder.Qty = inventoryModel.AvailableQty - instruct.Qty;
                                    putawayOrder.MaterialId = inventoryModel.MaterialId;
                                    putawayOrder.MaterialCode = inventoryModel.MaterialCode;
                                    putawayOrder.MaterialName = inventoryModel.MaterialName;
                                    putawayOrder.MaterialKeyId = inventoryModel.MaterialKeyId;
                                    putawayOrder.SourceType = 1;
                                    putawayOrder.CreateDate = DateTime.Now;
                                    putawayOrder.Roadway = inventoryModel.RoutewayId.ToString();
                                    _putawayOrderRepository.AddEntity(putawayOrder);
                                    result = _unitOfWork.SaveChangesEntity();
                                    if (!result)
                                    {
                                        message = "保存上架单失败！";
                                        _unitOfWork.RollbackChanges();
                                        return false;
                                    }
                                }
                            }
                        }
                        inventoryModel.AvailableQty -= instruct.Qty;
                        inventoryModel.AllocateQty -= instruct.Qty;
                        inventoryModel.IsLock = false;
                        inventoryModel.Status = 3;
                        inventoryModel.Remark = string.Empty;
                        _inventoryRepository.UpdEntity(inventoryModel);


                    }
                    //库存流水
                    var inventoryLog = new InventoryLog
                    {
                        Id = YitIdHelper.NextId(),
                        SourceType = 1,
                        SourceSn = shippingOrderDetail.OrderSn,
                        WarehouseId = shippingOrderDetail.WarehouseId,
                        WarehouseName = shippingOrderDetail.WarehouseName,
                        AreaName = shippingOrderDetail.AreaName,
                        LocationCode = inventoryModel.LocationCode,
                        PalletBarcode = inventoryModel.PalletBarcode,
                        MaterialId = inventoryModel.MaterialId,
                        MaterialCode = inventoryModel.MaterialCode,
                        MaterialName = inventoryModel.MaterialName,
                        BatchNo = inventoryModel.BatchNo,
                        StartQty = startQty,
                        ChangeQty = -changeQty,
                        EndQty = startQty - changeQty,
                        BaseUnitId = inventoryModel.UnitId,
                        BaseUnitName = inventoryModel.UnitName,
                        CreateDate = DateTime.Now,
                    };
                    _inventoryLogRepository.AddEntity(inventoryLog);
                    result = _unitOfWork.SaveChangesEntity();
                    if (!result)
                    {
                        message = "保存库存流水失败！";
                        _unitOfWork.RollbackChanges();
                        return false;
                    }
                }

                var shiplockOrderDetail = _shippingLockCellRepository.QueryEntityWhere(d => d.Id == pickobj.RelatedOrderDetailId);
                var shippingOrder=_shippingOrderDetailRepository.QueryEntityWhere(d => d.Id == shiplockOrderDetail.OrderDetailId);

                var aa = _inventoryRepository.GetEntityAll();
                var ilist = _inventoryRepository.GetEntityAll().Where(x => x.PalletBarcode == pickobj.PalletBarcode);
                   
                if (shippingOrder != null && shippingOrder.AreaCode.Contains("P"))
                {
                    ilist=ilist.Where(d => d.Id == shiplockOrderDetail.InventoryId);
                }
                
                foreach (var item in ilist)
                {
                    if (item.AreaCode.Contains('P'))
                    {
                        item.Status = 1;
                        item.IsLock = false;
                    }
                    else
                    {
                        item.IsLock = false;
                    }
                }
                var picklist = _pickingOrderRepository.GetEntityWhereAll(x => x.SourceType == 2 && x.Status == 4 && x.PalletBarcode == pickobj.PalletBarcode);
                if (shippingOrder != null && shippingOrder.AreaCode.Contains("P"))
                {
                    picklist=picklist.Where(d => d.RelatedOrderDetailId == shiplockOrderDetail.Id);
                }
                foreach (var item in picklist)
                {
                    item.Status = 5;
                    item.ModifyDate = DateTime.Now;
                    _pickingOrderRepository.UpdEntity(item);
                }
                if (_unitOfWork.SaveChangesEntity())
                {
                    if (!Config.IsDevErp)
                    {
                        if (IsNullPallet)
                        {
                            var pickobj1 = _pickingOrderRepository.QueryEntityWhere(x => x.Code == pickcode && x.SourceType == 2 && x.Status == 5);
                            var cell = _cellRepository.QueryEntityWhere(d => d.Code == pickobj1.LocationCode);

                            //出库单明细表
                            var shippingLockCell = _shippingLockCellRepository.QueryEntityWhere(d => d.Id == pickobj1.RelatedOrderDetailId);
                            //出库单
                            var shippingOrderDetail = _shippingOrderDetailRepository.QueryEntityWhere(d => d.Id == shippingLockCell.OrderDetailId);
                            //库存表
                            var inventory = _inventoryRepository.QueryEntityWhere(d => d.Id == shippingLockCell.InventoryId);
                            //获取物料信息
                            var modelSpec = string.Empty;
                            var UnitName = string.Empty;
                            if (!string.IsNullOrEmpty(pickobj1.MaterialCode))
                            {
                                var material = _materialRepository.QueryEntityWhere(d => d.Code == pickobj1.MaterialCode);
                                modelSpec = material.ModelSpec;
                                UnitName = material.UnitName;
                            }
                            var stockCode = string.Empty;
                            var stockPlace = string.Empty;
                            var isvmi = string.Empty;
                            //获取库存信息
                            if (!string.IsNullOrEmpty(shippingLockCell.StockCode))
                            {
                                var stock = stockRepository.QueryEntityWhere(d => d.StockCode == shippingLockCell.StockCode);
                                stockCode = stock.StockCode;
                                stockPlace = stock.SPGroupCode;
                                if (stock.StockName.Contains("VMI"))
                                {
                                    isvmi = "Y";
                                }
                                else
                                {
                                    isvmi = "N";
                                }
                            }
                            var supplierCode = string.Empty;
                            //入库，库存供应商
                            if (!string.IsNullOrEmpty(shippingLockCell.SupplierName))
                            {
                                var supplier = _supplierRepository.QueryEntityWhere(d => d.Code == shippingLockCell.SupplierCode);
                                if (isvmi == "Y")
                                {
                                    supplierCode = supplier.Code;
                                }
                                supplierCode = "";
                            }
                            var wwsupplierCode = string.Empty;
                            ///委外加工的供应商
                            if (!string.IsNullOrEmpty(shippingLockCell.SupplierName))
                            {
                                var supplier = _supplierRepository.QueryEntityWhere(d => d.Name == shippingLockCell.SupplierName);

                                wwsupplierCode = supplier.Code;
                            }
                            //生产领料
                            if (shippingOrderDetail.PurOrderLineType == 3 || shippingOrderDetail.PurOrderLineType == 4)
                            {
                                BackUseingOutStockDto backuseingOutstock = new BackUseingOutStockDto
                                {
                                    Entry = new List<BackUseingOutStockDeatilDto>()
                                };
                                backuseingOutstock.BillId = shippingOrderDetail.Id;
                                backuseingOutstock.BillDate = shippingOrderDetail.BillDate.ToString("yyyy-MM-dd");
                                backuseingOutstock.DepartmentName = shippingOrderDetail.DeptName;
                                backuseingOutstock.DepartmentNumber = shippingOrderDetail.DeptCode;
                                backuseingOutstock.useing = "";
                                backuseingOutstock.SourceType = shippingOrderDetail.PurOrderLineNo;
                                backuseingOutstock.SourceNo = shippingOrderDetail.OrderSn;
                                BackUseingOutStockDeatilDto entry = new BackUseingOutStockDeatilDto
                                {
                                    Number = shippingLockCell.MaterialCode,
                                    Name = shippingLockCell.MaterialName,
                                    BatchNo = shippingLockCell.BatchNo,
                                    Model = modelSpec,
                                    Unit = UnitName,
                                    Qty = (decimal)pickobj1.Qty,
                                    IsVMI = isvmi,
                                    SupplierNumber = supplierCode,
                                    StockNumber = stockCode,
                                    StockPlace = cell.LogicalPartName,
                                };
                                backuseingOutstock.Entry.Add(entry);

                                #region 回传参数
                                string targeUrl = "http://59.110.231.187:9883/api/1";
                                try
                                {
                                    var jsonData = JsonConvert.SerializeObject(backuseingOutstock);
                                    var resultt = _httpClientHelper.PostAsync<WcsTaskResultDto>(
                                        targeUrl,
                                        jsonData,
                                        "application/json"
                                    ).Result;

                                    if (resultt?.Code != EmApiResCode.Success)
                                    {
                                        message = resultt?.Msg ?? "ERP接口调用生产领料失败";
                                        return false;
                                    }
                                    resultt.Data = backuseingOutstock.BillId;

                                    return true;
                                }
                                catch (Exception e)
                                {
                                    message = e.Message;
                                    return false;
                                }
                                #endregion

                            }
                            //委外出库
                            if (shippingOrderDetail.PurOrderLineType == 5 || shippingOrderDetail.PurOrderLineType == 6)
                            {
                                BackSubcontractOutStockDto backSubcontractOutStock = new BackSubcontractOutStockDto
                                {
                                    Entry = new List<BackSubcontractOutStockDetailDto>()
                                };


                                backSubcontractOutStock.BillId = shippingOrderDetail.Id;
                                backSubcontractOutStock.BillDate = shippingOrderDetail.BillDate.ToString("yyyy-MM-dd");
                                backSubcontractOutStock.SupplierNumber = wwsupplierCode;
                                backSubcontractOutStock.OrderType = shippingOrderDetail.PurOrderLineNo;

                                BackSubcontractOutStockDetailDto entry = new BackSubcontractOutStockDetailDto
                                {
                                    Number = shippingLockCell.MaterialCode,
                                    Name = shippingLockCell.MaterialName,
                                    BatchNo = shippingLockCell.BatchNo,
                                    Model = modelSpec,
                                    Unit = UnitName,
                                    Qty = (decimal)pickobj1.Qty,
                                    IsVMI = isvmi,
                                    SupplierNumber = supplierCode,
                                    StockNumber = stockCode,
                                    StockPlace = cell.LogicalPartName,
                                };
                                backSubcontractOutStock.Entry.Add(entry);



                                #region 回传参数
                                string targeUrl = "http://59.110.231.187:9883/api/1";
                                try
                                {
                                    var jsonData = JsonConvert.SerializeObject(backSubcontractOutStock);
                                    var resultt = _httpClientHelper.PostAsync<WcsTaskResultDto>(
                                        targeUrl,
                                        jsonData,
                                        "application/json"
                                    ).Result;

                                    if (resultt?.Code != EmApiResCode.Success)
                                    {
                                        message = resultt?.Msg ?? "ERP接口调用委外出库失败";
                                        return false;
                                    }
                                    resultt.Data = backSubcontractOutStock.BillId;

                                    return true;
                                }
                                catch (Exception e)
                                {
                                    message = e.Message;
                                    return false;
                                }
                                #endregion

                            }
                            //其他出库
                            if (!string.IsNullOrEmpty(shippingOrderDetail.OtherTypeCode))
                            {
                                var othertype = _otherTypeRepository.QueryEntityWhere(d => d.TypeCode == shippingOrderDetail.OtherTypeCode);
                                BackOtherOutStockDto backOtherOutStock = new BackOtherOutStockDto
                                {
                                    Entry = new List<BackOtherOutStockDetailDto>()
                                };
                                backOtherOutStock.BillId = shippingOrderDetail.Id;
                                backOtherOutStock.BillDate = shippingOrderDetail.BillDate.ToString("yyyy-MM-dd");
                                backOtherOutStock.SupplierNumber = wwsupplierCode;
                                backOtherOutStock.BillType = othertype.TypeName;
                                BackOtherOutStockDetailDto entry = new BackOtherOutStockDetailDto
                                {
                                    Number = shippingLockCell.MaterialCode,
                                    Name = shippingLockCell.MaterialName,
                                    BatchNo = shippingLockCell.BatchNo,
                                    Model = modelSpec,
                                    Unit = UnitName,
                                    Qty = (decimal)pickobj1.Qty,
                                    IsVMI = isvmi,
                                    SupplierNumber = supplierCode,
                                    StockNumber = stockCode,
                                    StockPlace = cell.LogicalPartName,
                                };
                                backOtherOutStock.Entry.Add(entry);

                                #region 回传参数
                                string targeUrl = "http://59.110.231.187:9883/api/1";
                                try
                                {
                                    var jsonData = JsonConvert.SerializeObject(backOtherOutStock);
                                    var resultt = _httpClientHelper.PostAsync<WcsTaskResultDto>(
                                        targeUrl,
                                        jsonData,
                                        "application/json"
                                    ).Result;

                                    if (resultt?.Code != EmApiResCode.Success)
                                    {
                                        message = resultt?.Msg ?? "ERP接口调用其他出库失败";
                                        return false;
                                    }
                                    resultt.Data = backOtherOutStock.BillId;

                                    return true;
                                }
                                catch (Exception e)
                                {
                                    message = e.Message;
                                    return false;
                                }
                                #endregion
                            }
                        }
                      
                    }

                 
                    return true;
                
            }
                




                #region !ispack
                //if (!ispack)
                //{
                //    #region AI
                //    //string nows = DateTime.Now.ToString("yyyyMMdd");
                //    //var latestPackageDetail = _packageDetailRepository.GetEntityAll().OrderByDescending(x => x.CreateDate).FirstOrDefault();
                //    //string basePackageCode;
                //    //if (latestPackageDetail != null)
                //    //    basePackageCode = latestPackageDetail.PackageCode.Substring(0, 8);
                //    //else
                //    //    basePackageCode = "19981111";

                //    //if (nows != basePackageCode)
                //    //{
                //    //    for (int i = 0; i < shippqty; i++)
                //    //    {
                //    //        PackageDetail packageDetail2 = new PackageDetail();
                //    //        packageDetail2 = packageDetail;
                //    //        packageDetail2.PackageCode = nows + "_1_1";
                //    //            // 其他属性赋值  
                //    //        _packageDetailRepository.AddEntity(packageDetail2);
                //    //        if (!_unitOfWork.SaveChangesEntity())
                //    //            return false;
                //    //    }
                //    //}
                //    //else
                //    //{
                //    //    for (int i = 0; i < shippqty; i++)
                //    //    {
                //    //        PackageDetail packageDetail2 = new PackageDetail();
                //    //        packageDetail2 = packageDetail;
                //    //        var existingPackageDetail = _packageDetailRepository.GetEntityAll()
                //    //            .OrderByDescending(x => x.CreateDate)
                //    //            .FirstOrDefault(x => x.OrderSn == packageDetail.OrderSn);

                //    //        if (existingPackageDetail != null)
                //    //        {
                //    //            string[] parts = existingPackageDetail.PackageCode.Split('_');
                //    //            int number = Convert.ToInt32(parts[parts.Length - 1]);
                //    //            number++;
                //    //            string prefix = existingPackageDetail.PackageCode.Substring(0, existingPackageDetail.PackageCode.LastIndexOf('_') + 1);
                //    //            packageDetail2.PackageCode = $"{prefix}{number}";
                //    //        }
                //    //        else
                //    //        {
                //    //            // 如果没有找到具有相同OrderSn的包裹，则基于最新的包裹代码生成新的包裹代码  
                //    //            string[] parts = latestPackageDetail.PackageCode.Split('_');
                //    //            int number = Convert.ToInt32(parts[1]);
                //    //            number++;
                //    //            string prefix = latestPackageDetail.PackageCode.Substring(0, 9); // 假设前缀是前8位日期加上一个下划线  
                //    //            packageDetail2.PackageCode = $"{prefix}{number}_1";
                //    //        }

                //    //        // 其他属性赋值  
                //    //        _packageDetailRepository.AddEntity(packageDetail2);
                //    //        if (!_unitOfWork.SaveChangesEntity())
                //    //            return false;
                //    //    }
                //    //}

                //    //return true;
                //    #endregion
                //    #region 非AI
                //    string nows = DateTime.Now.ToString("yyyyMMdd");
                //    for (int i = 0; i < shippqty; i++)
                //    {
                //        PackageDetail packageDetail2 = new PackageDetail();
                //        packageDetail2 = packageDetail;
                //        var aa = _packageDetailRepository.GetEntityAll().OrderByDescending(x => x.CreateDate).FirstOrDefault()?.PackageCode;
                //        if (aa != null)
                //            aa = aa.Substring(0, 8);
                //        else
                //            aa = "19981111";
                //        if (nows != aa)
                //        {
                //            //packageDetail2.PackageCode = nows + "_1_1";
                //            packageDetail2.PackageCode = nows + "_" + shippqty + "_1";
                //            _packageDetailRepository.AddEntity(packageDetail2);
                //        }
                //        else
                //        {
                //            var bb = _packageDetailRepository.GetEntityAll().OrderByDescending(x => x.CreateDate).FirstOrDefault(x => x.OrderSn == packageDetail2.OrderSn);
                //            if (bb != null)
                //            {
                //                //有-该最后一位  
                //                string[] parts = bb.PackageCode.Split('_');
                //                string firstNumbers = parts[parts.Length - 1];
                //                int number = Convert.ToInt32(firstNumbers);
                //                number++;
                //                string cc = bb.PackageCode.Substring(0, bb.PackageCode.LastIndexOf('_')) + "_";
                //                packageDetail2.PackageCode = $"{cc}{number}";
                //                _packageDetailRepository.AddEntity(packageDetail2);
                //            }
                //            else
                //            {
                //                //var cc = _packageDetailRepository.GetEntityAll().OrderByDescending(x => x.CreateDate).FirstOrDefault()?.PackageCode;
                //                //if (cc == null)
                //                //{
                //                //    message = "包裹号出问题了！";
                //                //    return false;
                //                //}
                //                //string[] parts = cc.Split('_');
                //                //string firstNumbers = parts[1];
                //                //int number = Convert.ToInt32(firstNumbers);
                //                //number++;
                //                //string dd = cc.Substring(0, 9);
                //                //packageDetail2.PackageCode = $"{dd}{number}" + "_1";
                //                //_packageDetailRepository.AddEntity(packageDetail2);
                //                packageDetail2.PackageCode = $"{nows}" + "_" + shippqty + "_1";
                //                _packageDetailRepository.AddEntity(packageDetail2);
                //            }
                //        }
                //        if (!_unitOfWork.SaveChangesEntity())
                //            return false;
                //    }
                //    #endregion
                //}
                #endregion

                    return false;
                
            }
            catch (Exception)
            {
                _unitOfWork.RollbackChanges();
                throw;
            }
        }

        public  bool FinishShippingOrderDetail(string putcode,out string message)
        {
            _unitOfWork.BeginTransaction();
            try
            {
                
                var result = StaticFinishShippingOrderDetail(putcode, out message);

                if (result)
                {
                    _unitOfWork.CommitChanges();
                    return true;

                }
                _unitOfWork.RollbackChanges();
                return false;
            }
            catch (Exception)
            {
                _unitOfWork.RollbackChanges();
                throw;
            }
        }

        public bool StartPickingShippingOrderDetail(StartInventoryDTO m, out string message)
        {
            message = string.Empty;
            string putcode = "";
            bool isWcs = false;
            bool result = false;
            //查询是否有此托盘
            var palletBarAll = _palletRepository.QueryEntityWhere(x => x.PalletBarcode == m.PalletCode);
            if (palletBarAll == null)
            {
                message = "未查询到此托盘";
                return false;
            }
            var pobj = _putawayOrderRepository.QueryEntityWhere(x => x.PalletBarcode == m.PalletCode && x.BillType == 2 && x.Status == 4);
            if (pobj != null)
            {
                message = "该托盘正在拣选作业中，请勿重复下发！";
                return false;
            }
            //根据托盘查找库存数据
            var inlist = _inventoryRepository.GetEntityWhereAll(x => x.PalletBarcode == m.PalletCode && x.Status == 3).ToList();
            _unitOfWork.BeginTransaction();
            try
            {
                if (!inlist.Any())
                {
                    message = "未找到库存数据";
                    _unitOfWork.RollbackChanges();
                    return false;
                }
                else
                {
                    var cell = _cellRepository.QueryEntityWhere(x => x.Code == inlist.First().LocationCode);
                    if (cell == null)
                    {
                        message = "仓位不存在！";
                        _unitOfWork.RollbackChanges();
                        return false;
                    }
                    #region 回库时获取一个新货位
                    StackingStorage stackingStorage = new StackingStorage()
                    {
                        AreaCode = cell.AreaCode,
                        MaterialId = inlist.FirstOrDefault()?.MaterialId,
                        BatchNo = inlist.FirstOrDefault()?.BatchNo,
                        YRid = cell.RoutewayId
                    };
                    if (GetCellCode(stackingStorage, out message))
                    {
                        string cellcode = "";
                        cellcode = message;
                        //锁仓位
                        var tcell = _cellRepository.QueryEntityWhere(x => x.Code == cellcode);
                        if (tcell != null)
                        {
                            cell.FullStatus = 0;
                            cell.IsLock = false;
                            cell.BusinessType = 0;
                            cell.ModifyDate = DateTime.Now;
                            _cellRepository.UpdEntity(cell);
                            tcell.BusinessType = 1;
                            tcell.IsLock = true;
                            tcell.FullStatus = 1;
                            tcell.ModifyDate = DateTime.Now;
                            _cellRepository.UpdEntity(tcell);
                            foreach (var item in inlist)
                            {
                                item.LocationId = tcell.Id;
                                item.LocationCode = tcell.Code;
                                item.LocationName = tcell.Name;
                                item.LocationLineNo = tcell.LineNo;
                                item.RoutewayId = tcell.RoutewayId;
                                item.LocationColumnNo = tcell.ColumnNo;
                                item.LocationLayerNo = tcell.LayerNo;
                                item.LocationDepth = tcell.DepthIndex;
                                item.LocationDistanceValue = Convert.ToInt32(tcell.IsMaxDepth);
                                _inventoryRepository.UpdEntity(item);
                                if (item.AreaCode.Contains("L"))
                                    isWcs = true;
                                Instruct instruct = new Instruct
                                {
                                    Status = 2,
                                    WarehouseCode = item.WarehouseCode,
                                    ToLocation = item.LocationCode,
                                    WorkDeviceType = 1,
                                    InstructType = 7,
                                    Action = 0,
                                    RelatedOrderId = item.RelatedOrderDetailId,
                                    ExpectedToLocation = item.LocationCode,
                                    InstructIndex = 1,
                                    PalletBarcode = m.PalletCode,
                                    Priority = 9999,
                                    Qty = (decimal)item.AvailableQty,
                                    BusinessType = (int)EmBusinessType.In,
                                };
                                _instructRepository.AddEntity(instruct);
                                string str = DateTime.Now.ToString("yyyyMMddHHmmssfff");
                                string putawayCode = "SRT" + str;
                                PutawayOrder putawayOrder = new PutawayOrder();
                                putawayOrder.Id = YitIdHelper.NextId();
                                putawayOrder.Code = putawayCode;
                                putawayOrder.BillType = 2;
                                putawayOrder.RelatedOrderDetailId = item.RelatedOrderDetailId;
                                putawayOrder.PalletBarcode = m.PalletCode;
                                putawayOrder.LocationCode = item.LocationCode;
                                putawayOrder.LocationDepth = item.LocationDepth == 0 ? null : item.LocationDepth;
                                putawayOrder.Status = 4;
                                putawayOrder.Qty = item.AvailableQty;
                                putawayOrder.MaterialId = item.MaterialId;
                                putawayOrder.MaterialCode = item.MaterialCode;
                                putawayOrder.MaterialName = item.MaterialName;
                                putawayOrder.MaterialKeyId = item.MaterialKeyId;
                                putawayOrder.SourceType = 1;
                                putawayOrder.CreateDate = DateTime.Now;
                                putawayOrder.Roadway = item.RoutewayId.ToString();

                                _putawayOrderRepository.AddEntity(putawayOrder);
                                result = _unitOfWork.SaveChangesEntity();
                                if (!result)
                                {
                                    message = "保存上架单失败！";
                                    _unitOfWork.RollbackChanges();
                                    return false;
                                }
                                putcode = putawayOrder.Code;
                            }
                            var pallobj = _palletRepository.QueryEntityWhere(x => x.LocationCode == cell.Code);
                            if (pallobj != null)
                            {
                                pallobj.LocationName = cell.Name;
                                pallobj.LocationCode = cell.Code;
                                _palletRepository.UpdEntity(pallobj);
                            }
                        }
                    }
                    #endregion         
                }
                if (result)
                {
                    if (!isWcs)
                    {
                        result = StaticFinishPickingShippingOrderDetail(putcode, out message);
                        if (result)
                        {
                            _unitOfWork.CommitChanges();
                            return true;
                        }
                        else
                        {
                            _unitOfWork.RollbackChanges();
                            return false;
                        }
                    }
                    _unitOfWork.CommitChanges();
                    return true;
                }
                _unitOfWork.RollbackChanges();
                return false;
            }
            catch (Exception)
            {

                throw;
            }

        }

        private bool StaticFinishPickingShippingOrderDetail(string putcode, out string message)
        {
            message = "";
            string PalletBarcode = "";
            var putobj = _putawayOrderRepository.QueryEntityWhere(x => x.Code == putcode && x.SourceType == 1 && x.Status == 4 && x.BillType == 2);
            if (putobj == null)
            {
                message = "找不到上架单！";
                return false;
            }
            PalletBarcode = putobj.PalletBarcode;
            var instructlist = _instructRepository.GetEntityWhereAll(x => x.PalletBarcode == PalletBarcode && x.Status == 2 && x.InstructType == 1 || (x.PalletBarcode == PalletBarcode && x.Status == 2 && x.InstructType == 7)).ToList();
            if (!instructlist.Any())
            {
                message = "未查询到上架单指令！";
                return false;
            }
            var invobjlist = _inventoryRepository.GetEntityWhereAll(x => x.PalletBarcode == PalletBarcode);
            try
            {
                if (invobjlist.Any())
                {
                    foreach (var item in invobjlist)
                    {
                        item.Status = 1;
                        if (item.Remark == "补货")
                            item.IsLock = true;
                    }
                }
                #region 补货逻辑处理
                var slist = _shippingOrderDetailRepository.GetEntityWhereAll(x => x.IsSuspend == true);
                if (slist.Any())
                {
                    Dictionary<long, ShippingOrderDetail> keyValuePairs1 = new Dictionary<long, ShippingOrderDetail>();
                    foreach (var item in slist)
                    {
                        keyValuePairs1.Add(item.Id, item);
                    }
                    bool IsOk = false;
                    var slocklist = _lockCellRepository.GetEntityAlls().ToList();
                    foreach (var item in keyValuePairs1)
                    {
                        var slocklists = slocklist.Where(x => x.OrderDetailId == item.Key);
                        foreach (var item2 in slocklists)
                        {
                            if (item2.InventoryQty < item2.OutQty)
                            {
                                IsOk = true;
                                break;
                            }
                            else
                                continue;
                        }
                        if (IsOk)
                            break;
                        else
                        {
                            var sobj = _shippingOrderDetailRepository.QueryEntityById(item.Key);
                            if (sobj == null)
                            {
                                message = "出库单信息有误！";
                                return false;
                            }
                            sobj.IsSuspend = false;
                        }
                    }
                    #region 弃用补货逻辑
                    //var sllist = _lockCellRepository.GetEntityWhereAll(x => x.PalletBarcode==PalletBarcode && x.IsPicking == false).ToList();                 
                    //if (sllist.Count>0)
                    //{
                    //    List<ShippingLockCell> slocklist = new List<ShippingLockCell>();
                    //    Dictionary<long, decimal?> keyValuePairs = new Dictionary<long, decimal?>();
                    //    foreach (var item3 in keyValuePairs1)
                    //    {
                    //        slocklist = sllist.Where(x => x.OrderDetailId == item3.Key && x.IsPicking == false && x.PalletBarcode == PalletBarcode).ToList();
                    //        foreach (var item in slocklist)
                    //        {
                    //            if (keyValuePairs.ContainsKey((long)item.InventoryId))
                    //                continue;
                    //            keyValuePairs.Add(item.InventoryId != null ? Convert.ToInt64(item.InventoryId) : 0, slocklist.Sum(x => x.OutQty));
                    //        }
                    //    }
                    //    foreach (var item in keyValuePairs)
                    //    {
                    //        var iobj = invobjlist.FirstOrDefault(x => x.Id == item.Key);
                    //        if (iobj == null)
                    //            continue;
                    //        if (item.Value <= iobj.AvailableQty)
                    //        {
                    //            long? shippingorderid = sllist.FirstOrDefault(x => x.InventoryId == iobj.Id)?.OrderDetailId;
                    //            if (shippingorderid == null)
                    //            {
                    //                message = "出库单明细信息有误！";
                    //                return false;
                    //            }
                    //            var sobj = keyValuePairs1.ContainsKey((long)shippingorderid) ? keyValuePairs1[(long)shippingorderid] : null;
                    //            if (sobj == null)
                    //            {
                    //                message = "找不到出库单！";
                    //                return false;
                    //            }
                    //            sobj.IsSuspend = false;
                    //            _shippingOrderDetailRepository.UpdEntity(sobj);
                    //        }
                    //    }
                    //}                
                    #endregion
                }
                #endregion
                foreach (var item in instructlist)
                {
                    item.Status = 4;
                    item.EndTime = DateTime.Now;
                    _instructRepository.UpdEntity(item);
                }
                var putlist = _putawayOrderRepository.GetEntityWhereAll(x => x.SourceType == 1 && x.Status == 4 && x.PalletBarcode == PalletBarcode && x.BillType == 2);
                foreach (var item in putlist)
                {
                    item.Status = 5;
                    item.Fifodate = DateTime.Now;
                    _putawayOrderRepository.UpdEntity(item);
                }
                var ilist = _inventoryRepository.GetEntityWhereAll(x => x.AvailableQty < x.AllocateQty && x.IsLock == false);
                foreach (var item in ilist)
                {
                    item.Status = 5;
                }
                return _unitOfWork.SaveChangesEntity();
            }
            catch (Exception)
            {
                _unitOfWork.RollbackChanges();
                throw;
            }

        }

        public bool FinishPickingShippingOrderDetail(string putcode, out string message)
        {
            _unitOfWork.BeginTransaction();
            try
            {
                bool result = StaticFinishPickingShippingOrderDetail(putcode, out message);
                if (result)
                {
                    _unitOfWork.CommitChanges();
                    return true;
                }
                _unitOfWork.RollbackChanges();
                return false;
            }
            catch (Exception)
            {
                _unitOfWork.RollbackChanges();
                throw;
            }
        }

        public StackingReceivingsDto? GetReceivingRoderData(string PalletCode, out string message)
        {
            message = string.Empty;

            var invlist = _inventoryRepository.GetEntityWhereAll(x => x.PalletBarcode == PalletCode && x.Status == 4 && x.IsLock == false);
            if (!invlist.Any())
            {
                message = "找不到库存信息";
                return null;
            }
            var putkobj = _putawayOrderRepository.QueryIsEntityWhere(x => x.PalletBarcode == PalletCode && x.Status == 4);
            if (putkobj != null)
            {
                message = "正在作业中！";
                return null;
            }
            StackingReceivingsDto srmodel = new StackingReceivingsDto();
            srmodel.PallteCode = PalletCode;
            foreach (var item in invlist)
            {
                if (item.RelatedOrderDetailId == null)
                {
                    message = "组垛入库关联id有误！";
                    return null;
                }
                srmodel.Cell = item.LocationCode;

                MaterNum maternum = new MaterNum();
                maternum.MaterialCode = item.MaterialCode;
                maternum.Num = item.AvailableQty;
                srmodel.materNum.Add(maternum);
            }

            return srmodel;
        }

        public bool StartShippingOutZeroQty(List<SubmitOutListDTO> OrderDTO, out string message)
        {
            message = string.Empty;
            try
            {
                bool result = false;
                _unitOfWork.BeginTransaction();

                foreach (var item in OrderDTO)
                {
                    //托盘条码
                    string pacode = item.PalletBarcode;

                    Inventory? inventoryModel = _inventoryRepository.QueryEntityById(item.OrderDetId);
                    //状态修改出库在途         
                    if (inventoryModel == null)
                    {
                        message = "获取库存信息失败！";
                        return false;
                    }
                    inventoryModel.Status = 4;
                    var inventorylist = _inventoryRepository.GetEntityWhereAll(x => x.PalletBarcode == pacode && x.Status == 1 || (x.PalletBarcode == pacode && x.Status == 5));
                    if (inventorylist.Any())
                    {
                        foreach (var item2 in inventorylist)
                        {
                            item2.IsLock = true;
                            item2.Status = 4;
                            _inventoryRepository.UpdEntity(item2);
                        }
                    }
                    var cellobj = _cellRepository.QueryEntityWhere(x => x.Code == inventoryModel.LocationCode);
                    if (cellobj == null)
                    {
                        message = "未查询到仓位" + inventoryModel.LocationCode;
                    }

                    #region 添加指令
                    Instruct inobj = new Instruct();
                    inobj.WarehouseCode = inventoryModel.WarehouseCode;
                    inobj.Status = 2;
                    inobj.FromLocation = item.StationCode;
                    inobj.ToLocation = inventoryModel.LocationCode;
                    inobj.WorkDeviceType = 1;
                    inobj.InstructType = 6;
                    inobj.Action = 0;
                    inobj.RelatedOrderId = 0;
                    inobj.ExpectedToLocation = inventoryModel.LocationCode;
                    inobj.InstructIndex = 1;
                    inobj.PalletBarcode = pacode;
                    inobj.ScanedBarcode = pacode;
                    inobj.Priority = 9999;
                    inobj.Qty = 0;
                    inobj.FinishedQty = 0;
                    inobj.BusinessType = (int)EmBusinessType.Out;
                    inobj.RelatedOrderDetailId = 0;
                    _instructRepository.AddEntity(inobj);
                    #endregion
                    #region 添加下架单
                    string str = DateTime.Now.ToString("yyyyMMddHHmmssfff");
                    string pickCode = "ORT" + str;
                    PickingOrder pickOrder = new PickingOrder();
                    pickOrder.Id = YitIdHelper.NextId();
                    pickOrder.Code = pickCode;
                    pickOrder.WarehouseCode = inventoryModel.WarehouseCode;
                    pickOrder.WarehouseName = inventoryModel.WarehouseName;
                    pickOrder.BillType = 2;
                    pickOrder.DescAddress = item.DescAddress;
                    pickOrder.PalletBarcode = pacode;
                    pickOrder.Roadway = cellobj.RoutewayId.ToString();
                    pickOrder.LocationCode = cellobj.Code;
                    pickOrder.LocationDepth = cellobj.DepthIndex;
                    pickOrder.Status = 4;
                    pickOrder.Qty = 0;
                    pickOrder.MaterialId = inventoryModel.MaterialId;
                    pickOrder.MaterialCode = inventoryModel.MaterialCode;
                    pickOrder.MaterialName = inventoryModel.MaterialName;
                    pickOrder.MaterialKeyId = inventoryModel.MaterialKeyId;
                    pickOrder.BatchNo = inventoryModel.BatchNo;
                    pickOrder.SourceType = 2;
                    pickOrder.RelatedOrderDetailId = 0;
                    pickOrder.CreateDate = DateTime.Now;
                    if (inventoryModel.AreaCode.Contains('L'))
                    {
                        var pickobj = _pickingOrderRepository.QueryEntityWhere(x => x.PalletBarcode == pacode && x.Status == 4 && x.SourceType == 2);
                        if (pickobj == null)
                        {
                            #region 堆垛机
                            ////获取巷道节点
                            //RoadwayCode roadwayCode = new RoadwayCode()
                            //{
                            //    taskCode = putawayOrder.Code,
                            //    Roadway = putawayOrder.Roadway,
                            //};

                            //var data = HttpHelper.SendPostRequestes("获取巷道节点", roadwayCode);
                            ////LogHelper.LogInformation("巷道节点" + data);
                            ////堆垛机出库
                            //TaskLiku taskLiku = new TaskLiku()
                            //{
                            //    taskCode = putawayOrder.Code,
                            //    taskType = "2",
                            //    startPoint = putawayOrder.LocationCode,
                            //    //endPositionId = OrderDTO.StationCode,
                            //    endPoint = data.data
                            //};
                            ////堆垛机出库和led屏幕显示
                            //var ip = LedipShow.Getledip(putawayOrder.SourceType, putawayOrder.Roadway);
                            //var start = putawayOrder.SourceType == 2 ? "出库" : "入库";
                            //var ledlik = HttpHelper.LedSendPostRequest(new { ip = ip, message = "物料号:" + putawayOrder.MaterialCode + "\\n" + "托盘码" + putawayOrder.PalletBarcode + "\\n" + "状态:" + start + "\\n位置:" + putawayOrder.SiteCode });
                            //var taskLikudata = HttpHelper.WCSSendPostRequest("Api/ApiWCS/ReceiveTask", taskLiku);
                            ////LogHelper.LogInformation("wcs出入库：" + taskLikudata);
                            #endregion
                        }
                    }
                    _pickingOrderRepository.AddEntity(pickOrder);
                    PickingOrderDetail pickOrderDetail = new PickingOrderDetail();
                    pickOrderDetail.Id = YitIdHelper.NextId();
                    pickOrderDetail.OrderId = pickOrder.Id;
                    pickOrderDetail.PalletBarcode = pacode;
                    pickOrderDetail.MaterialBarcode = inventoryModel.MaterialCode;
                    _pickingOrderDetailRepository.AddEntity(pickOrderDetail);
                    #endregion
                    result = _unitOfWork.SaveChangesEntity();
                    if (!result)
                    {
                        message = "出库解绑失败";
                        return false;
                    }
                }
                if (result)
                {
                    message = "操作成功！";
                    _unitOfWork.CommitChanges();
                    return true;
                }
                _unitOfWork.RollbackChanges();
                return false;
            }
            catch (Exception)
            {
                _unitOfWork.RollbackChanges();
                throw;
            }
        }

        private bool StaticFinishShippingOutZeroQty(string pickcode, out string message)
        {
            message = "";
            string PalletBarcode = "";
            var pickobj = _pickingOrderRepository.QueryEntityWhere(x => x.Code == pickcode && x.SourceType == 2 && x.Status == 4 && x.BillType == 2);
            if (pickobj == null)
            {
                message = "找不到下架单！";
                return false;
            }
            PalletBarcode = pickobj.PalletBarcode;
            var instructlist = _instructRepository.GetEntityWhereAll(x => x.PalletBarcode == PalletBarcode && x.Status == 2 && x.InstructType == 6).ToList();
            if (!instructlist.Any())
            {
                message = "未查询到上架单指令！";
                return false;
            }
            try
            {
                foreach (var item in instructlist)
                {
                    item.Status = 4;
                    item.EndTime = DateTime.Now;
                    _instructRepository.UpdEntity(item);
                }
                var ilist = _inventoryRepository.GetEntityWhereAll(x => x.PalletBarcode == PalletBarcode && x.Status == 4).ToList();
                if (ilist.Any())
                {
                    foreach (var item in ilist)
                    {
                        item.IsLock = false;
                        _inventoryRepository.UpdEntity(item);
                        Instruct instruct2 = new Instruct
                        {
                            Status = 2,
                            WarehouseCode = item.WarehouseCode,
                            ToLocation = item.LocationCode,
                            WorkDeviceType = 1,
                            InstructType = 7,
                            Action = 0,
                            RelatedOrderId = item.RelatedOrderDetailId,
                            ExpectedToLocation = item.LocationCode,
                            InstructIndex = 1,
                            PalletBarcode = item.PalletBarcode,
                            Priority = 9999,
                            Qty = (decimal)item.AvailableQty,
                            BusinessType = (int)EmBusinessType.In,
                        };
                        _instructRepository.AddEntity(instruct2);
                        string str = DateTime.Now.ToString("yyyyMMddHHmmssfff");
                        string putawayCode = "SRT" + str;
                        PutawayOrder putawayOrder = new PutawayOrder();
                        putawayOrder.Id = YitIdHelper.NextId();
                        putawayOrder.Code = putawayCode;
                        putawayOrder.BillType = 2;
                        putawayOrder.RelatedOrderDetailId = item.RelatedOrderDetailId;
                        putawayOrder.PalletBarcode = item.PalletBarcode;
                        putawayOrder.LocationCode = item.LocationCode;
                        putawayOrder.LocationDepth = item.LocationDepth == 0 ? null : item.LocationDepth;
                        putawayOrder.Status = 4;
                        putawayOrder.Qty = item.AvailableQty;
                        putawayOrder.MaterialId = item.MaterialId;
                        putawayOrder.MaterialCode = item.MaterialCode;
                        putawayOrder.MaterialName = item.MaterialName;
                        putawayOrder.MaterialKeyId = item.MaterialKeyId;
                        putawayOrder.SourceType = 1;
                        putawayOrder.CreateDate = DateTime.Now;
                        putawayOrder.Roadway = item.RoutewayId.ToString();
                        _putawayOrderRepository.AddEntity(putawayOrder);
                    }
                }
                var picklist = _pickingOrderRepository.GetEntityWhereAll(x => x.SourceType == 2 && x.Status == 4 && x.PalletBarcode == PalletBarcode && x.BillType == 2);
                foreach (var item in picklist)
                {
                    item.Status = 5;
                    //item.Fifodate = DateTime.Now;
                    _pickingOrderRepository.UpdEntity(item);
                }
                if (_unitOfWork.SaveChangesEntity())
                {
                    try
                    {
                        string winFormsAppPath = @"D:\桌面\PrintBQ\帅佳\帅佳\bin\Debug\net6.0-windows\帅佳.exe";

                        // 你要传递给WinForms应用的参数  
                        string parameter = $"入,托盘：{pickobj.PalletBarcode},物料：{pickobj.MaterialName} 数量：{pickobj.Qty}";

                        // 使用Process.Start启动WinForms应用并传递参数  
                        Process.Start(winFormsAppPath, parameter);
                    }
                    catch (Exception ex)
                    {
                        message = "操作成功了，但打印异常！" + ex.Message;
                    }
                    return true;
                }
                return false;
            }
            catch (Exception)
            {
                _unitOfWork.RollbackChanges();
                throw;
            }
        }

        public bool FinishShippingOutZeroQty(string pickcode, out string message)
        {
            _unitOfWork.BeginTransaction();
            try
            {
                bool result = StaticFinishShippingOutZeroQty(pickcode, out message);
                if (result)
                {
                    _unitOfWork.CommitChanges();
                    return true;
                }
                _unitOfWork.RollbackChanges();
                return false;
            }
            catch (Exception)
            {
                _unitOfWork.RollbackChanges();
                throw;
            }
        }

        public bool UpdShippingLockCellStatus2(string PalletCode, out string message)
        {
            message = string.Empty;
            var clist = _cachePortRepository.GetEntityAll();
            var plist = _packRepository.GetEntityAll();
            var PackCode = "";
            _unitOfWork.BeginTransaction();
            try
            {
                var slockobj = _lockCellRepository.GetEntityWhereAll(x => x.PalletBarcode == PalletCode && x.Status == 1).ToList();
                foreach (var item in slockobj)
                {
                    if (item.Status == 1)
                    {
                        item.Status = 2;
                        var reordersn = _lockCellRepository.QueryEntityWhere(x => x.Status == 2 && x.OrdeSn == item.OrdeSn)?.CachePortCode;
                        if (!string.IsNullOrEmpty(reordersn))
                        {
                            item.CachePortCode = reordersn;
                            _lockCellRepository.UpdEntity(item);
                        }
                        else
                        {
                            var cobj = clist.FirstOrDefault(x => x.IsUsed == false && x.Status == 1);
                            if (cobj == null)
                            {
                                item.CachePortCode = clist.First().Code;
                                _lockCellRepository.UpdEntity(item);
                            }
                            else
                            {
                                item.CachePortCode = cobj.Code;
                                cobj.IsUsed = true;
                                _cachePortRepository.UpdEntity(cobj);
                            }
                        }
                        PackCode = item.PackCode;
                    }
                    else
                    {
                        message = "未知错误！";
                        return false;
                    }
                }
                var pobj = _packRepository.QueryEntityWhere(x => x.Code == PackCode);
                if (pobj != null)
                {
                    pobj.IsUsed = false;
                    _packRepository.UpdEntity(pobj);
                }
                else
                {
                    message = "打包台信息有误！";
                    _unitOfWork.RollbackChanges();
                    return false;
                }
                if (_unitOfWork.SaveChangesEntity())
                {
                    _unitOfWork.CommitChanges();
                    return true;
                }
                _unitOfWork.RollbackChanges();
                return false;
            }
            catch (Exception)
            {
                _unitOfWork.RollbackChanges();
                throw;
            }
        }

        public bool UpdShippingLockCellStatus4(string PalletCode, out string message)
        {
            message = string.Empty;
            var clist = _cachePortRepository.GetEntityAll();
            var CachePortCode = "";
            _unitOfWork.BeginTransaction();
            try
            {
                var slockobj = _lockCellRepository.GetEntityWhereAll(x => x.PalletBarcode == PalletCode && x.Status == 2).ToList();
                foreach (var item in slockobj)
                {
                    if (item.Status == 2)
                    {
                        item.Status = 4;
                        _lockCellRepository.UpdEntity(item);
                    }
                    else
                    {
                        message = "未知错误！";
                        return false;
                    }
                    CachePortCode = item.CachePortCode;
                }
                var cobj = clist.FirstOrDefault(x => x.Code == CachePortCode);
                if (cobj != null)
                {
                    cobj.IsUsed = false;
                    _cachePortRepository.UpdEntity(cobj);
                }
                else
                {
                    message = "打包台信息有误！";
                    _unitOfWork.RollbackChanges();
                    return false;
                }
                if (_unitOfWork.SaveChangesEntity())
                {
                    _unitOfWork.CommitChanges();
                    return true;
                }
                _unitOfWork.RollbackChanges();
                return false;
            }
            catch (Exception)
            {

                throw;
            }
        }

        public PackCachePortDto? GetPackCachePort(string PalletCode, out string message)
        {
            message = string.Empty;
            var slist = _lockCellRepository.GetEntityWhereAll(x => x.PalletBarcode == PalletCode && x.Status == 1);
            if (!slist.Any())
            {
                message = "暂时无任务！";
                return null;
            }
            PackCachePortDto srmodel = new PackCachePortDto();
            foreach (var item in slist)
            {
                srmodel.OrderNo = item.OrdeSn;
                srmodel.PallteCode = PalletCode;
                PackCachePortCode maternum = new PackCachePortCode();
                maternum.MaterialCode = item.MaterialCode;
                maternum.Num = item.OutQty;
                maternum.PackCode = item.PackCode;
                maternum.CachePortCode = item.CachePortCode;
                srmodel.packCachePortCodes.Add(maternum);
            }
            return srmodel;
        }

        public PackCachePortDto? GetPackCachePort2(string PalletCode, out string message)
        {
            message = string.Empty;
            var slist = _lockCellRepository.GetEntityWhereAll(x => x.PalletBarcode == PalletCode && x.Status == 2);
            if (!slist.Any())
            {
                message = "暂时无任务！";
                return null;
            }
            PackCachePortDto srmodel = new PackCachePortDto();
            foreach (var item in slist)
            {
                srmodel.OrderNo = item.OrdeSn;
                srmodel.PallteCode = PalletCode;
                PackCachePortCode maternum = new PackCachePortCode();
                maternum.MaterialCode = item.MaterialCode;
                maternum.Num = item.OutQty;
                maternum.PackCode = item.PackCode;
                maternum.CachePortCode = item.CachePortCode;
                srmodel.packCachePortCodes.Add(maternum);
            }
            return srmodel;
        }
        #region 打包/暂存区
        public List<ShippingOrderDetailGroupDTO> GetShippingLockCellPackList(string? order, int pageIndex, int pageSize, out int totalCount)
        {
            var slist = _lockCellRepository.GetEntityAlls().Where(x => x.Status == 1);
            if (!string.IsNullOrEmpty(order))
                slist = slist.Where(x => x.OrdeSn.Contains(order));
            var slists = slist.ToList();
            var slgroutp = slists.GroupBy(x => x.OrdeSn);
            List<ShippingOrderDetailGroupDTO> resList = new List<ShippingOrderDetailGroupDTO>();
            foreach (var item in slgroutp)
            {
                ShippingOrderDetailGroupDTO? shippingOrderDetailGroupDTO = new ShippingOrderDetailGroupDTO();
                shippingOrderDetailGroupDTO.OrderSn = item.Key;
                shippingOrderDetailGroupDTO.CheckedAll = false;
                shippingOrderDetailGroupDTO.LockCells = new List<ShippingLockCell>();
                var lockCells = slists.Where(x => x.OrdeSn == item.Key);
                if (!lockCells.Any())
                    continue;
                shippingOrderDetailGroupDTO.LockCells = lockCells.ToList();
                resList.Add(shippingOrderDetailGroupDTO);
            }
            totalCount = resList.Count;
            resList = resList.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();

            return resList;

        }

        public List<ShippingOrderDetailCachePortGroupDTO> GetShippingLockCellCachePortList(string? order, int? status, DateTime startdate, DateTime enddate, int pageIndex, int pageSize, out int totalCount)
        {
            var list = _packageDetailRepository.GetEntityAlls();

            if (status != null)
                list = list.Where(x => x.Status == status);

            if (!string.IsNullOrEmpty(order))
                list = list.Where(x => x.OrderSn.Contains(order));

            if (startdate != DateTime.MinValue && enddate != DateTime.MinValue)
                list = list.Where(x => x.CreateDate >= startdate && x.CreateDate < enddate.AddDays(1));
            else if (startdate != DateTime.MinValue)
                list = list.Where(x => x.CreateDate >= startdate);
            else if (enddate != DateTime.MinValue)
                list = list.Where(x => x.CreateDate < enddate.AddDays(1));
            var lists = list.ToList();
            var slgroutp = lists.GroupBy(x => x.OrderSn);
            var locklist = _lockCellRepository.GetEntityAlls().ToList();
            List<ShippingOrderDetailCachePortGroupDTO> shippingOrderDetailCachePortGroupDTOs = new List<ShippingOrderDetailCachePortGroupDTO>();

            foreach (var item in slgroutp)
            {
                ShippingOrderDetailCachePortGroupDTO? shippingOrderDetailGroupDTO = new ShippingOrderDetailCachePortGroupDTO();
                shippingOrderDetailGroupDTO.OrderSn = item.Key;
                shippingOrderDetailGroupDTO.CheckedAll = false;
                shippingOrderDetailGroupDTO.Status = locklist.FirstOrDefault(x => x.OrdeSn == item.Key)?.Status;
                shippingOrderDetailGroupDTO.packageDetails = new List<PackageDetail>();
                var plist = list.Where(x => x.OrderSn == item.Key);
                if (!plist.Any())
                    continue;
                shippingOrderDetailGroupDTO.packageDetails = plist.ToList();
                shippingOrderDetailCachePortGroupDTOs.Add(shippingOrderDetailGroupDTO);
            }
            totalCount = shippingOrderDetailCachePortGroupDTOs.Count;
            shippingOrderDetailCachePortGroupDTOs = shippingOrderDetailCachePortGroupDTOs.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();

            return shippingOrderDetailCachePortGroupDTOs;
        }

        public bool UpdShippingLockCellStatus2(List<ShippingLockPackDto> ids, out string message)
        {
            message = string.Empty;
            var clist = _cachePortRepository.GetEntityAll();
            var slist = _shippingOrderDetailRepository.GetEntityAll();
            var sllist = _lockCellRepository.GetEntityAll();
            string packcode = "";
            bool result = false;
            _unitOfWork.BeginTransaction();
            try
            {
                Dictionary<int, string> keyValuePairs = new Dictionary<int, string>();
                foreach (var item in ids)
                {
                    var sobj = slist.FirstOrDefault(x => x.Id == item.Id);
                    if (sobj == null)
                    {
                        message = "找不到出库单！";
                        _unitOfWork.RollbackChanges();
                        return false;
                    }
                    var slockobj = sllist.FirstOrDefault(x => x.OrderDetailId == sobj.Id);
                    if (slockobj == null)
                    {
                        message = "找不到明细单！";
                        _unitOfWork.RollbackChanges();
                        return false;
                    }

                    packcode = slockobj.PackCode;
                    if (slockobj.Status == 1)
                    {
                        #region 弃用
                        //var slocklists = _lockCellRepository.GetEntityWhereAll(x => x.Status == 1 && x.PackCode == slockobj.PackCode);
                        //if (!slocklists.Any())
                        //{
                        //    var pobj = _packRepository.QueryEntityWhere(x => x.Code == slockobj.PackCode);
                        //    if (pobj != null)
                        //    {
                        //        pobj.IsUsed = false;
                        //        _packRepository.UpdEntity(pobj);
                        //        result = _unitOfWork.SaveChangesEntity();
                        //        if (!result)
                        //        {
                        //            _unitOfWork.RollbackChanges();
                        //            return false;
                        //        }
                        //    }
                        //}
                        #endregion
                        #region
                        sobj.PackQty += item.PackQty;
                        if (sobj.PackQty > sobj.Qty)
                        {
                            message = "数量超出！";
                            return false;
                        }
                        //暂存区
                        var reordersn = _lockCellRepository.QueryEntityWhere(x => (x.Status == 2 || x.Status == 1) && x.OrdeSn == slockobj.OrdeSn)?.CachePortCode;
                        if (!string.IsNullOrEmpty(reordersn))
                        {
                            if (sobj.PackQty == sobj.Qty)
                                slockobj.Status = 2;
                            slockobj.CachePortCode = reordersn;
                            _lockCellRepository.UpdEntity(slockobj);
                        }
                        else
                        {
                            var cacheportobj = clist.FirstOrDefault(x => x.IsUsed == false && x.Status == 1);
                            if (cacheportobj != null)
                            {
                                if (sobj.PackQty == sobj.Qty)
                                    slockobj.Status = 2;
                                slockobj.CachePortCode = cacheportobj.Code;
                                cacheportobj.IsUsed = true;
                                _cachePortRepository.UpdEntity(cacheportobj);
                                _lockCellRepository.UpdEntity(slockobj);
                            }
                            else
                            {
                                if (sobj.PackQty == sobj.Qty)
                                    slockobj.Status = 2;
                                slockobj.CachePortCode = clist.First().Code;
                                _lockCellRepository.UpdEntity(slockobj);
                            }
                        }
                        #region 非AI
                        string nows = DateTime.Now.ToString("yyyyMMdd");
                        var aa = _packageDetailRepository.GetEntityAll().OrderByDescending(x => x.CreateDate).FirstOrDefault()?.PackageCode;
                        if (aa != null)
                            aa = aa.Substring(0, 8);
                        else
                            aa = "19981111";
                        PackageDetail packageDetail = new PackageDetail();
                        packageDetail.RelatedOrderDetailId = slockobj.Id;
                        packageDetail.OrderSn = slockobj.OrdeSn;
                        packageDetail.MaterialId = slockobj.MaterialId;
                        packageDetail.MaterialName = slockobj.MaterialName;
                        packageDetail.MaterialCode = slockobj.MaterialCode;
                        packageDetail.BatchNO = slockobj.BatchNo;
                        packageDetail.UnitId = sobj.UnitId;
                        packageDetail.UnitName = sobj.UnitName;
                        packageDetail.QTY = item.PackQty;
                        if (nows != aa)
                        {

                            if (!keyValuePairs.ContainsKey(item.PackNo))
                            {
                                keyValuePairs.Add(item.PackNo, nows + "_S_1");
                                packageDetail.PackageCode = nows + "_S_1";
                            }
                            else
                                packageDetail.PackageCode = keyValuePairs[item.PackNo];
                            _packageDetailRepository.AddEntity(packageDetail);
                        }
                        else
                        {
                            var bb = _packageDetailRepository.GetEntityAll().OrderByDescending(x => x.CreateDate).FirstOrDefault(x => x.OrderSn == packageDetail.OrderSn && x.PackageCode.Contains("S"));
                            if (bb != null)
                            {
                                if (!keyValuePairs.ContainsKey(item.PackNo))
                                {
                                    //有-该最后一位  
                                    string[] parts = bb.PackageCode.Split('_');
                                    string firstNumbers = parts[parts.Length - 1];
                                    int number = Convert.ToInt32(firstNumbers);
                                    number++;
                                    string cc = bb.PackageCode.Substring(0, bb.PackageCode.LastIndexOf('_')) + "_";
                                    packageDetail.PackageCode = $"{cc}{number}";
                                    keyValuePairs.Add(item.PackNo, packageDetail.PackageCode);
                                }
                                else
                                    packageDetail.PackageCode = keyValuePairs[item.PackNo];

                                _packageDetailRepository.AddEntity(packageDetail);
                            }
                            else
                            {
                                var cc = _packageDetailRepository.GetEntityAll().OrderByDescending(x => x.CreateDate).FirstOrDefault()?.PackageCode;
                                if (cc == null)
                                {
                                    message = "包裹号出问题了！";
                                    return false;
                                }

                                if (!keyValuePairs.ContainsKey(item.PackNo))
                                {
                                    //string[] parts = cc.Split('_');
                                    //string firstNumbers = parts[1];
                                    //int number = Convert.ToInt32(firstNumbers);
                                    //number++;
                                    //string dd = cc.Substring(0, 9);
                                    //packageDetail.PackageCode = $"{dd}{number}" + "_1";
                                    //keyValuePairs.Add(item.PackNo, packageDetail.PackageCode);
                                    keyValuePairs.Add(item.PackNo, nows + "_S_1");
                                    packageDetail.PackageCode = nows + "_S_1";
                                }
                                else
                                    packageDetail.PackageCode = keyValuePairs[item.PackNo];

                                _packageDetailRepository.AddEntity(packageDetail);
                            }
                        }
                        if (!_unitOfWork.SaveChangesEntity())
                        {
                            _unitOfWork.RollbackChanges();
                            return false;
                        }
                        #endregion             
                        #endregion
                    }
                    else
                    {
                        message = "未知错误！";
                        return false;
                    }
                }
                //result = _unitOfWork.SaveChangesEntity();
                //if (!result)
                //{
                //    _unitOfWork.RollbackChanges();
                //    return false;
                //}

                var slocklists = _lockCellRepository.QueryEntityWhere(x => x.Status == 1 && x.PackCode == packcode);
                if (slocklists == null)
                {
                    var pobj = _packRepository.QueryEntityWhere(x => x.Code == packcode);
                    if (pobj != null)
                    {
                        pobj.IsUsed = false;
                        _packRepository.UpdEntity(pobj);
                        result = _unitOfWork.SaveChangesEntity();
                        if (!result)
                        {
                            _unitOfWork.RollbackChanges();
                            return false;
                        }
                    }
                }
                //if (_unitOfWork.SaveChangesEntity())
                //{
                //    _unitOfWork.CommitChanges();
                //    return true;
                //}
                //_unitOfWork.RollbackChanges();
                _unitOfWork.CommitChanges();
                return true;
            }
            catch (Exception)
            {

                throw;
            }

        }

        public bool UpdShippingLockCellStatus4(List<long> ids, out string message)
        {
            message = string.Empty;
            var idss = ids.Distinct().ToList();
            var clist = _cachePortRepository.GetEntityAll();
            var plist = _packRepository.GetEntityAll();
            var palist = _packageDetailRepository.GetEntityAll();
            bool result = false;
            _unitOfWork.BeginTransaction();
            try
            {
                foreach (var id in idss)
                {
                    var slocklistss = _lockCellRepository.GetEntityAll();
                    var slockobj = _lockCellRepository.QueryEntityById(id);
                    if (slockobj == null)
                    {
                        message = "找不到明细单！";
                        _unitOfWork.RollbackChanges();
                        return false;
                    }
                    var slockorderobj = slocklistss.FirstOrDefault(x => x.OrdeSn == slockobj.OrdeSn && x.Status == 1);
                    if (slockorderobj != null)
                    {
                        message = "改单号下还有打包任务未完成，无法发货！";
                        _unitOfWork.RollbackChanges();
                        return false;
                    }
                    if (slockobj.Status == 4)
                    {
                        message = "当前包裹已发货，请勿重复操作！";
                        _unitOfWork.RollbackChanges();
                        return false;
                    }
                    if (slockobj.Status == 2)
                    {
                        var packagedlist = palist.Where(x => x.RelatedOrderDetailId == id && x.Status == 1);
                        if (packagedlist == null)
                        {
                            message = "找不到发货信息，或该任务已完成！";
                            _unitOfWork.RollbackChanges();
                            return false;
                        }
                        foreach (var item in packagedlist)
                        {
                            item.Status = 0;
                            _packageDetailRepository.UpdEntity(item);
                        }
                        slockobj.Status = 4;

                        result = _unitOfWork.SaveChangesEntity();
                        if (!result)
                        {
                            _unitOfWork.RollbackChanges();
                            return false;
                        }
                        var slocklists = slocklistss.Where(x => x.Status == 2 && x.CachePortCode == slockobj.CachePortCode);
                        if (!slocklists.Any())
                        {
                            var cobj = clist.FirstOrDefault(x => x.Code == slockobj.CachePortCode);
                            if (cobj != null)
                            {
                                cobj.IsUsed = false;
                                _cachePortRepository.UpdEntity(cobj);
                                result = _unitOfWork.SaveChangesEntity();
                                if (!result)
                                {
                                    _unitOfWork.RollbackChanges();
                                    return false;
                                }
                            }
                        }
                    }
                    else
                    {
                        message = "未知错误！";
                        return false;
                    }
                }
                if (result)
                {
                    _unitOfWork.CommitChanges();
                    return true;
                }
                _unitOfWork.RollbackChanges();
                return false;
            }
            catch (Exception)
            {

                throw;
            }

        }
        #endregion
        #endregion

        #region 机械爪
        public bool GetEmptyPalletBarcode(out string message)
        {
            message = string.Empty;
            var invlist = _inventoryRepository.GetEntityWhereAll(x => x.MaterialName == "空托盘" && x.IsLock == false && x.Status == 1);
            if (!invlist.Any())
            {
                message = "库中没有可用的托盘了！";
                return false;
            }
            string palletbarcode = "";
            foreach (var item in invlist.ToList())
            {
                string rows = item.LocationCode.Substring(7, 1);
                if (rows == "1")
                {
                    string[] parts = item.LocationCode.Substring(5).Split(separator: '_');
                    int rou = Convert.ToInt32(parts[0]); // 巷道是第一个数字
                    int row = Convert.ToInt32(parts[1]);    // 排是第二个数字
                    int col = Convert.ToInt32(parts[2]);    // 列是第三个数字
                    int lev = Convert.ToInt32(parts[3]);  // 层是第
                    string modifiedcellcode = $"Cell:{rou}_2_{col}_{lev}_1";
                    var inventorycell = _inventoryRepository.QueryEntityWhere(x => x.LocationCode == modifiedcellcode);
                    if (inventorycell != null)
                        continue;
                    else
                    {
                        palletbarcode = item.PalletBarcode;
                        break;
                    }
                }
                else if (rows == "4")
                {
                    string[] parts = item.LocationCode.Substring(5).Split(separator: '_');
                    int rou = Convert.ToInt32(parts[0]); // 巷道是第一个数字
                    int row = Convert.ToInt32(parts[1]);    // 排是第二个数字
                    int col = Convert.ToInt32(parts[2]);    // 列是第三个数字
                    int lev = Convert.ToInt32(parts[3]);  // 层是第
                    string modifiedcellcode = $"Cell:{rou}_3_{col}_{lev}_1";
                    var inventorycell = _inventoryRepository.QueryEntityWhere(x => x.LocationCode == modifiedcellcode);
                    if (inventorycell != null)
                        continue;
                    else
                    {
                        palletbarcode = item.PalletBarcode;
                        break;
                    }
                }
                else
                {
                    palletbarcode = item.PalletBarcode;
                    break;
                }
            }
            var inventoryModel = _inventoryRepository.QueryEntityWhere(x => x.PalletBarcode == palletbarcode);

            if (inventoryModel == null)
            {
                message = "库中没有可用的托盘了！";
                return false;
            }

            inventoryModel.IsLock = true;
            inventoryModel.Status = 4;

            #region 添加指令
            Instruct inobj = new Instruct();
            inobj.WarehouseCode = inventoryModel.WarehouseCode;
            inobj.Status = 2;
            inobj.ToLocation = inventoryModel.LocationCode;
            inobj.WorkDeviceType = 1;
            inobj.InstructType = 12;
            inobj.Action = 0;
            inobj.RelatedOrderId = 0;
            inobj.ExpectedToLocation = inventoryModel.LocationCode;
            inobj.InstructIndex = 1;
            inobj.PalletBarcode = inventoryModel.PalletBarcode;
            inobj.ScanedBarcode = inventoryModel.PalletBarcode;
            inobj.Priority = 9999;
            inobj.Qty = 1;
            inobj.FinishedQty = 0;
            inobj.BusinessType = (int)EmBusinessType.Out;
            inobj.RelatedOrderDetailId = 0;
            inobj.CreateUserId = 0;
            inobj.CreateUserName = "PLC请求";
            _instructRepository.AddEntity(inobj);
            #endregion
            #region 添加下架单
            string str = DateTime.Now.ToString("yyyyMMddHHmmssfff");
            string pickCode = "KTP" + str;
            PickingOrder pickOrder = new PickingOrder();
            pickOrder.Id = YitIdHelper.NextId();
            pickOrder.Code = pickCode;
            pickOrder.WarehouseCode = inventoryModel.WarehouseCode;
            pickOrder.WarehouseName = inventoryModel.WarehouseName;
            pickOrder.BillType = 1;
            pickOrder.PalletBarcode = inventoryModel.PalletBarcode;
            pickOrder.LocationCode = inventoryModel.LocationCode;
            pickOrder.LocationDepth = inventoryModel.LocationDepth;
            pickOrder.Status = 4;
            pickOrder.Qty = 1;
            pickOrder.MaterialId = inventoryModel.MaterialId;
            pickOrder.MaterialCode = inventoryModel.MaterialCode;
            pickOrder.MaterialName = inventoryModel.MaterialName;
            pickOrder.MaterialKeyId = inventoryModel.MaterialKeyId;
            pickOrder.BatchNo = inventoryModel.BatchNo;
            pickOrder.SourceType = 2;
            pickOrder.RelatedOrderDetailId = 0;
            pickOrder.CreateDate = DateTime.Now;
            _pickingOrderRepository.AddEntity(pickOrder);
            //PickingOrderDetail pickOrderDetail = new PickingOrderDetail();
            //pickOrderDetail.Id = YitIdHelper.NextId();
            //pickOrderDetail.OrderId = pickOrder.Id;
            //pickOrderDetail.PalletBarcode = inventoryModel.PalletBarcode;
            //pickOrderDetail.MaterialBarcode = inventoryModel.MaterialCode;
            //_pickingOrderDetailRepository.AddEntity(pickOrderDetail);
            #endregion
            if (_unitOfWork.SaveChangesEntity())
            {
                _unitOfWork.CommitChanges();
                message = palletbarcode;
                return true;
            }
            _unitOfWork.RollbackChanges();
            return false;
        }

        public bool FinishEmptyPalletBarcode(string pickcode, out string message)
        {
            message = string.Empty;
            var pickobj = _pickingOrderRepository.QueryEntityWhere(x => x.Code == pickcode && x.SourceType == 2 && x.Status == 4);
            if (pickobj == null)
            {
                message = "找不到下架单！";
                return false;
            }
            string? pallbarcode = pickobj.PalletBarcode;
            if (string.IsNullOrEmpty(pallbarcode))
            {
                message = "托盘信息有误！";
                return false;
            }
            var instruct = _instructRepository.QueryEntityWhere(x => x.PalletBarcode == pallbarcode && x.Status == 2 && x.InstructType == 12);
            if (instruct == null)
            {
                message = "找不到该指令";
                return false;
            }
            else
            {
                instruct.Status = 4;
                instruct.EndTime = DateTime.Now;
                if (instruct.RelatedOrderId != 0)
                {
                    var sobj = _shippingOrderDetailRepository.QueryEntityById(instruct.RelatedOrderId ?? 0);
                    if (sobj != null)
                    {
                        sobj.Status = 4;
                        var sdobj = _lockCellRepository.QueryEntityById(instruct.RelatedOrderDetailId ?? 0);
                        if (sdobj != null)
                            sdobj.Status = 4;
                    }
                }
            }
            _unitOfWork.BeginTransaction();
            try
            {
                var tell = _cellRepository.QueryEntityWhere(x => x.Code == instruct.ExpectedToLocation);
                if (tell == null)
                {
                    message = "未查询到仓位！";
                    _unitOfWork.RollbackChanges();
                    return false;
                }
                else
                {
                    tell.FullStatus = 0;
                    tell.IsLock = false;
                    tell.BusinessType = 0;
                }
                var invobj = _inventoryRepository.QueryEntityWhere(x => x.PalletBarcode == pallbarcode && x.LocationCode == tell.Code);
                if (invobj == null)
                {
                    message = "库存信息有误！";
                    return false;
                }
                else
                    _inventoryRepository.DelEntity(invobj);
                var pallobj = _palletRepository.QueryEntityWhere(x => x.LocationCode == tell.Code && x.LocationName == tell.Name);
                if (pallobj != null)
                {
                    pallobj.LocationName = string.Empty;
                    pallobj.LocationCode = string.Empty;
                }
                pickobj.Status = 5;
                if (_unitOfWork.SaveChangesEntity())
                {
                    _unitOfWork.CommitChanges();
                    return true;
                }
                _unitOfWork.RollbackChanges();
                return false;
            }
            catch (Exception)
            {
                _unitOfWork.RollbackChanges();
                throw;
            }
        }

        public List<WcsTaskResultDtos>? WCSOutTask(OutTaskNoticeReqDto m, out string message)
        {
            message = "";
            var isMaterialCode = _materialRepository.QueryIsEntityWhere(x => x.Code == m.MaterialCode) == null;
            if (isMaterialCode)
            {
                message = $"{m.MaterialCode}不存在于WMS中";
                return null;
            }
            var invenlist = _inventoryRepository.GetEntityWhereAll(x => x.MaterialCode == m.MaterialCode && x.Status == 1 && x.IsLock == false);
            if (!invenlist.Any())
            {
                message = $"{m.MaterialCode}在WMS中无库存";
                return null;
            }
            bool result = false;
            string tpalletbarcode = "";
            string tlocationcode = "";
            bool istran = false;
            bool tresult = false;
            string ttlocationcode = "";
            try
            {
                int c = 0;
                List<WcsTaskResultDtos> wcsTaskResultDtos = new List<WcsTaskResultDtos>();

                foreach (var item in invenlist.ToList())
                {
                    _unitOfWork.BeginTransaction();
                    if (c == m.PalletQty)
                        break;
                    tpalletbarcode = string.Empty;
                    tlocationcode = string.Empty;
                    ttlocationcode = string.Empty;
                    istran = false;
                    #region 自动移库
                    //排
                    string rows = item.LocationCode.Substring(7, 1);
                    if (string.IsNullOrEmpty(rows))
                    {
                        message = "获取仓位排失败！";
                        return null;
                    }
                    if (rows == "1")
                    {
                        string[] parts = item.LocationCode.Substring(5).Split(separator: '_');
                        int rou = Convert.ToInt32(parts[0]); // 巷道是第一个数字
                        int row = Convert.ToInt32(parts[1]);    // 排是第二个数字
                        int col = Convert.ToInt32(parts[2]);    // 列是第三个数字
                        int lev = Convert.ToInt32(parts[3]);  // 层是第
                        string modifiedcellcode = $"Cell:{rou}_2_{col}_{lev}_1";
                        var inventorycell = _inventoryRepository.QueryEntityWhere(x => x.LocationCode == modifiedcellcode);
                        if (inventorycell != null && inventorycell.Status == 1)
                        {
                            tpalletbarcode = inventorycell.PalletBarcode;
                            tlocationcode = inventorycell.LocationCode;
                            istran = true;
                            tresult = ShippingTransferBinInventory(item.LocationCode, inventorycell.LocationCode, inventorycell.AreaCode, inventorycell.RoutewayId, inventorycell.PalletBarcode, out message);
                            if (!tresult)
                            {
                                _unitOfWork.RollbackChanges();
                                return null;
                            }
                        }
                        else if (inventorycell != null && inventorycell.Status == 2)
                        {
                            message = $"浅货位{modifiedcellcode}有任务正在作业中，稍后再试！";
                            _unitOfWork.RollbackChanges();
                            return null;
                        }
                    }
                    else if (rows == "4")
                    {
                        string[] parts = item.LocationCode.Substring(5).Split(separator: '_');
                        int rou = Convert.ToInt32(parts[0]); // 巷道是第一个数字
                        int row = Convert.ToInt32(parts[1]);    // 排是第二个数字
                        int col = Convert.ToInt32(parts[2]);    // 列是第三个数字
                        int lev = Convert.ToInt32(parts[3]);  // 层是第
                        string modifiedcellcode = $"Cell:{rou}_3_{col}_{lev}_1";
                        var inventorycell = _inventoryRepository.QueryEntityWhere(x => x.LocationCode == modifiedcellcode);
                        if (inventorycell != null && inventorycell.Status == 1)
                        {
                            tpalletbarcode = inventorycell.PalletBarcode;
                            tlocationcode = inventorycell.LocationCode;
                            istran = true;
                            tresult = ShippingTransferBinInventory(item.LocationCode, inventorycell.LocationCode, inventorycell.AreaCode, inventorycell.RoutewayId, inventorycell.PalletBarcode, out message);
                            if (!tresult)
                            {
                                _unitOfWork.RollbackChanges();
                                return null;
                            }
                        }
                        else if (inventorycell != null && inventorycell.Status == 2)
                        {
                            message = $"浅货位{modifiedcellcode}有任务正在作业中，稍后再试！";
                            _unitOfWork.RollbackChanges();
                            return null;
                        }
                    }
                    #endregion
                    ShippingOrderDetail sobj = new ShippingOrderDetail
                    {
                        BillType = 1,
                        OrderSn = m.OrderSn,
                        Status = 3,
                        ShippedQty = 0,
                        SourceType = 4,
                        IsSuspend = false,
                        AreaCode = item.AreaCode,
                        AreaName = item.AreaName,
                        WarehouseId = item.WarehouseId,
                        WarehouseCode = item.WarehouseCode,
                        WarehouseName = item.WarehouseName,
                        MaterialId = item.MaterialId == null ? 0 : Convert.ToInt64(item.MaterialId),
                        MaterialName = item.MaterialName,
                        MaterialCode = item.MaterialCode,
                        MaterialTypeCode = item.MaterialTypeCode,
                        UnitId = item.UnitId,
                        UnitName = item.UnitName,
                        BatchNo = item.BatchNo,
                        Qty = item.AvailableQty,
                        CreateUserId = 0,
                        CreateUserName = "WCS"
                    };
                    _shippingOrderDetailRepository.AddEntity(sobj);
                    result = _unitOfWork.SaveChangesEntity();
                    if (!result)
                        break;
                    item.PickedQty += item.OutQty;
                    item.AllocateQty += item.OutQty;
                    item.IsLock = true;
                    _inventoryRepository.UpdEntity(item);

                    ShippingLockCell sdobj = new ShippingLockCell
                    {
                        OrderDetailId = sobj.Id,
                        OrdeSn = m.OrderSn,
                        InventoryId = item.Id,
                        CellId = item.LocationId,
                        CellCode = item.LocationCode,
                        CellName = item.LocationName,
                        CellDepthIndex = item.LocationDepth,
                        WhId = item.WarehouseId,
                        OutQty = item.AvailableQty,
                        InventoryQty = item.AvailableQty,
                        PalletBarcode = item.PalletBarcode,
                        MaterialId = item.MaterialId,
                        MaterialCode = item.MaterialCode,
                        MaterialName = item.MaterialName,
                        MaterialKeyId = item.MaterialKeyId,
                        RoutewayId = item.RoutewayId,
                        BatchNo = item.BatchNo,
                        CreateUserId = 0,
                        CreateUserName = "WCS",
                        Status = 3
                    };
                    _lockCellRepository.AddEntity(sdobj);
                    result = _unitOfWork.SaveChangesEntity();
                    if (!result)
                        break;
                    #region 添加指令
                    Instruct inobj = new Instruct();
                    inobj.WarehouseCode = item.WarehouseCode;
                    inobj.Status = 2;
                    inobj.ToLocation = item.LocationCode;
                    inobj.WorkDeviceType = 1;
                    inobj.InstructType = 12;
                    inobj.Action = 0;
                    inobj.RelatedOrderId = sobj.Id;
                    inobj.ExpectedToLocation = item.LocationCode;
                    inobj.InstructIndex = 1;
                    inobj.PalletBarcode = item.PalletBarcode;
                    inobj.ScanedBarcode = item.PalletBarcode;
                    inobj.Priority = 9999;
                    inobj.Qty = item.AvailableQty ?? 0;
                    inobj.BusinessType = (int)EmBusinessType.Out;
                    inobj.RelatedOrderDetailId = sdobj.Id;
                    inobj.CreateUserId = 0;
                    inobj.CreateUserName = "WCS请求";
                    _instructRepository.AddEntity(inobj);
                    #endregion
                    #region 添加下架单
                    string str = DateTime.Now.ToString("yyyyMMddHHmmssfff");
                    string pickCode = "KTP" + str;
                    PickingOrder pickOrder = new PickingOrder();
                    pickOrder.Id = YitIdHelper.NextId();
                    pickOrder.Code = pickCode;
                    pickOrder.WarehouseCode = item.WarehouseCode;
                    pickOrder.WarehouseName = item.WarehouseName;
                    pickOrder.BillType = 1;
                    pickOrder.PalletBarcode = item.PalletBarcode;
                    pickOrder.LocationCode = item.LocationCode;
                    pickOrder.LocationDepth = item.LocationDepth;
                    pickOrder.Status = 4;
                    pickOrder.Qty = item.AvailableQty;
                    pickOrder.MaterialId = item.MaterialId;
                    pickOrder.MaterialCode = item.MaterialCode;
                    pickOrder.MaterialName = item.MaterialName;
                    pickOrder.MaterialKeyId = item.MaterialKeyId;
                    pickOrder.BatchNo = item.BatchNo;
                    pickOrder.SourceType = 2;
                    pickOrder.RelatedOrderDetailId = sdobj.Id;
                    pickOrder.CreateDate = DateTime.Now;
                    _pickingOrderRepository.AddEntity(pickOrder);
                    #endregion
                    result = _unitOfWork.SaveChangesEntity();
                    if (result)
                    {
                        if (Config.IsDev == false)
                        {
                            if (istran)
                            {
                                var putobj = _putawayOrderRepository.QueryEntityWhere(x => x.PalletBarcode == tpalletbarcode && x.Status == 4 && x.SourceType == 3);
                                if (putobj == null)
                                {
                                    message = "找不到上架单信息！";
                                    _unitOfWork.RollbackChanges();
                                    return null;
                                }
                                //移库
                                WcsTranTaskDto wcsTaskDto = new WcsTranTaskDto
                                {
                                    TaskCode = putobj.Code,
                                    FromTunnel = Convert.ToInt32(tlocationcode.Substring(5, 1)),
                                    FromRow = Convert.ToInt32(tlocationcode.Substring(7, 1)),
                                    FromBay = Convert.ToInt32(tlocationcode.Substring(9, 1)),
                                    FromLevel = Convert.ToInt32(tlocationcode.Substring(11, 1)),
                                    ToTunnel = Convert.ToInt32(putobj.LocationCode.Substring(5, 1)),
                                    ToRow = Convert.ToInt32(putobj.LocationCode.Substring(7, 1)),
                                    ToBay = Convert.ToInt32(putobj.LocationCode.Substring(9, 1)),
                                    ToLevel = Convert.ToInt32(putobj.LocationCode.Substring(11, 1)),
                                    PalletCode = putobj.PalletBarcode,
                                };
                                var wcsresult = _wcsHttpClient.TranTaskApi(wcsTaskDto);
                                if (wcsresult.Code != EmApiResCode.Success)
                                {
                                    message = wcsresult.ReturnInfo;
                                    result = false;
                                    _unitOfWork.RollbackChanges();
                                    break;
                                }
                                else
                                {
                                    ttlocationcode = putobj.LocationCode;
                                    InterfaceLog interfaceLog = new InterfaceLog();
                                    interfaceLog.Name = "SendMoveTask";
                                    interfaceLog.Url = "wcs/ExternalApi/SendMoveTask";
                                    interfaceLog.CallWay = 2;
                                    interfaceLog.CallWayStr = "POST";
                                    interfaceLog.InParam = JsonConvert.SerializeObject(m);
                                    interfaceLog.OutParam = wcsresult.ReturnInfo + $"(移库)托盘{tpalletbarcode}原仓位{tlocationcode}已被移动至{ttlocationcode}";
                                    interfaceLog.ExecDate = DateTime.Now;
                                    interfaceLog.FinishedDate = DateTime.Now;
                                    interfaceLog.Status = 1;
                                    _interfaceLogRepository.AddEntity(interfaceLog);
                                    _unitOfWork.SaveChangesEntity();
                                }
                            }
                        }
                        message = "操作成功！";
                        _unitOfWork.CommitChanges();
                    }
                    else
                    {
                        _unitOfWork.RollbackChanges();
                        return null;
                    }
                    string[] parts2 = pickOrder.LocationCode.Substring(5).Split(separator: '_');
                    WcsTaskResultDtos wcsTaskResultDtos1 = new WcsTaskResultDtos
                    {
                        TaskCode = pickOrder.Code,
                        Tunnel = Convert.ToInt32(parts2[0]),
                        Row = Convert.ToInt32(parts2[1]),
                        Bay = Convert.ToInt32(parts2[2]),
                        Level = Convert.ToInt32(parts2[3]),
                        Palletcode = pickOrder.PalletBarcode,
                        Count = pickOrder.Qty
                    };
                    if (wcsTaskResultDtos1.Tunnel == 3)
                        wcsTaskResultDtos1.Station = EmStation.S107;
                    else
                        wcsTaskResultDtos1.Station = EmStation.S106;
                    wcsTaskResultDtos.Add(wcsTaskResultDtos1);
                    Thread.Sleep(3000);
                    c++;
                }
                return wcsTaskResultDtos;

            }
            catch (Exception)
            {
                _unitOfWork.RollbackChanges();
                throw;
            }
        }
        #endregion

        /// <summary>
        /// 拣选回库时兄弟仓位
        /// </summary>
        /// <param name="m"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        private bool GetCellCode(StackingStorage m, out string message)
        {
            message = string.Empty;
            if (string.IsNullOrEmpty(m.AreaCode))
            {
                message = "库区编码有误！";
                return false;
            }
            //获取所有库区
            var areaobj = _areaRepository.QueryIsEntityWhere(x => x.Code == m.AreaCode && x.Status == 1);
            if (areaobj == null || areaobj.WhId == null)
            {
                message = "库区不存在或已被禁用!";
                return false;
            }
            long? wid = areaobj.WhId;
            //获取所有库房
            var warehouseobj = _warehouseRepository.QueryIsEntityWhere(x => x.Id == wid && x.Status == 1);
            if (warehouseobj == null)
            {
                message = "库房不存在或已被禁用!";
                return false;
            }

            //获取所有巷道
            var routewayQuery = _routewayRepository.GetEntityWhereAll(x => x.WhId == wid && x.Status == 1);
            if (!routewayQuery.Any())
            {
                message = "无可用巷道!";
                return false;
            }
            var allroutewayid = routewayQuery.Select(x => x.Id).ToList();
            allroutewayid = allroutewayid.OrderByDescending(x => x).ToList();
            foreach (var rid in allroutewayid)
            {
                //获取所有货架
                var shelves = _shelfRepository.GetEntityWhereAll(x => x.WhId == wid && x.AreaId == areaobj.Id && x.Status == 1 && x.RoutewayId == rid);
                if (!shelves.Any())
                {
                    message = "无可用货架!";
                    continue;
                }
                List<long> enabledShelves = shelves.Select(t => t.Id).ToList();//只取货架id
                var allcell = _cellRepository.GetEntityWhereAll(x => enabledShelves.Contains(x.ShelfId ?? 0) && x.Status == 1 && x.FullStatus == 0 && x.BusinessType == 0 && x.IsLock == false).ToList();
                int ycount = 0;
                int ncount = 0;
                long routewayid = 0;
                //默认找最深的
                bool ismaxdepth = true;
                ycount = allcell.Where(x => x.RoutewayId == rid && x.IsMaxDepth == true).Count();
                ncount = allcell.Where(x => x.RoutewayId == rid && x.IsMaxDepth == false).Count();
                //深的2个 浅的是1个
                if (ycount <= 1)
                {
                    if (ncount <= 1)
                        continue;
                    ismaxdepth = false;
                    routewayid = rid;
                }
                else
                {
                    routewayid = rid;
                }
                if (routewayid == 0)
                {
                    message = "无可用仓位！";
                    continue;
                }

                #region 兄弟仓位
                var invlist = _inventoryRepository.GetEntityWhereAll(x => x.MaterialId == m.MaterialId && x.BatchNo == m.BatchNo && x.LocationDistanceValue == 1 && x.Status == 1 && x.IsLock == false && x.RoutewayId == routewayid);
                if (invlist.Any() && ncount > 1)
                {
                    foreach (var item in invlist.ToList())
                    {
                        //排
                        string rows = item.LocationCode.Substring(7, 1);
                        if (string.IsNullOrEmpty(rows))
                        {
                            message = "获取仓位排失败！";
                            continue;
                        }
                        if (rows == "1")
                        {
                            string[] parts = item.LocationCode.Substring(5).Split(separator: '_');
                            int rou = Convert.ToInt32(parts[0]); // 巷道是第一个数字
                            int row = Convert.ToInt32(parts[1]);    // 排是第二个数字
                            int col = Convert.ToInt32(parts[2]);    // 列是第三个数字
                            int lev = Convert.ToInt32(parts[3]);  // 层是第
                            string modifiedcellcode = $"Cell:{rou}_2_{col}_{lev}_1";
                            var inventorycell = _inventoryRepository.QueryEntityWhere(x => x.LocationCode == modifiedcellcode);
                            if (inventorycell != null)
                                continue;
                            else
                            {
                                message = modifiedcellcode;
                                return true;
                            }
                        }
                        else if (rows == "4")
                        {
                            string[] parts = item.LocationCode.Substring(5).Split(separator: '_');
                            int rou = Convert.ToInt32(parts[0]); // 巷道是第一个数字
                            int row = Convert.ToInt32(parts[1]);    // 排是第二个数字
                            int col = Convert.ToInt32(parts[2]);    // 列是第三个数字
                            int lev = Convert.ToInt32(parts[3]);  // 层是第
                            string modifiedcellcode = $"Cell:{rou}_3_{col}_{lev}_1";
                            var inventorycell = _inventoryRepository.QueryEntityWhere(x => x.LocationCode == modifiedcellcode);
                            if (inventorycell != null)
                                continue;
                            else
                            {
                                message = modifiedcellcode;
                                return true;
                            }
                        }
                    }
                }

                #endregion
                var cellQuery = _cellRepository.GetEntityWhereAll(x => x.AreaCode == m.AreaCode && x.Status == 1 && x.FullStatus == 0 && x.IsLock == false && x.BusinessType == 0 && enabledShelves.Contains(x.ShelfId ?? 0));
                if (!cellQuery.Any())
                {
                    message = "无可用仓位!";
                    continue;
                }
                if (ismaxdepth)
                {
                    var cellsIsMaxDepths = cellQuery.Where(x => x.IsMaxDepth == true).OrderByDescending(c => c.DepthIndex)
                                  .ThenBy(c => c.LayerNo)
                                  .ThenBy(c => c.ColumnNo)
                                  .ThenBy(c => c.LineNo).ToList();
                    foreach (var item in cellsIsMaxDepths)
                    {
                        //排
                        string rows = item.Code.Substring(7, 1);
                        if (string.IsNullOrEmpty(rows))
                        {
                            message = "获取仓位排失败！";
                            continue;
                        }
                        if (rows == "1")
                        {
                            string[] parts = item.Code.Substring(5).Split(separator: '_');
                            int rou = Convert.ToInt32(parts[0]); // 巷道是第一个数字
                            int row = Convert.ToInt32(parts[1]);    // 排是第二个数字
                            int col = Convert.ToInt32(parts[2]);    // 列是第三个数字
                            int lev = Convert.ToInt32(parts[3]);  // 层是第
                            string modifiedcellcode = $"Cell:{rou}_2_{col}_{lev}_1";
                            var inventorycell = _inventoryRepository.QueryEntityWhere(x => x.LocationCode == modifiedcellcode);
                            if (inventorycell != null)
                                continue;
                            else
                            {
                                message = item.Code;
                                return true;
                            }
                        }
                        else if (rows == "4")
                        {
                            string[] parts = item.Code.Substring(5).Split(separator: '_');
                            int rou = Convert.ToInt32(parts[0]); // 巷道是第一个数字
                            int row = Convert.ToInt32(parts[1]);    // 排是第二个数字
                            int col = Convert.ToInt32(parts[2]);    // 列是第三个数字
                            int lev = Convert.ToInt32(parts[3]);  // 层是第
                            string modifiedcellcode = $"Cell:{rou}_3_{col}_{lev}_1";
                            var inventorycell = _inventoryRepository.QueryEntityWhere(x => x.LocationCode == modifiedcellcode);
                            if (inventorycell != null)
                                continue;
                            else
                            {
                                message = item.Code;
                                return true;
                            }
                        }
                    }
                }
                var cellsIsMaxDepths2 = cellQuery.Where(x => x.IsMaxDepth == false).OrderByDescending(c => c.DepthIndex)
                             .ThenBy(c => c.LayerNo)
                             .ThenBy(c => c.ColumnNo)
                             .ThenBy(c => c.LineNo).ToList();
                foreach (var item in cellsIsMaxDepths2)
                {
                    //排
                    string rows = item.Code.Substring(7, 1);
                    if (string.IsNullOrEmpty(rows))
                    {
                        message = "获取仓位排失败！";
                        continue;
                    }
                    if (rows == "2")
                    {
                        string[] parts = item.Code.Substring(5).Split(separator: '_');
                        int rou = Convert.ToInt32(parts[0]); // 巷道是第一个数字
                        int row = Convert.ToInt32(parts[1]);    // 排是第二个数字
                        int col = Convert.ToInt32(parts[2]);    // 列是第三个数字
                        int lev = Convert.ToInt32(parts[3]);  // 层是第
                        string modifiedcellcode = $"Cell:{rou}_1_{col}_{lev}_2";
                        var inventorycell = _inventoryRepository.QueryEntityWhere(x => x.LocationCode == modifiedcellcode);
                        if (inventorycell != null && inventorycell.Status == 1)
                        {
                            message = item.Code;
                            return true;
                        }
                        else
                            continue;
                    }
                    else if (rows == "3")
                    {
                        string[] parts = item.Code.Substring(5).Split(separator: '_');
                        int rou = Convert.ToInt32(parts[0]); // 巷道是第一个数字
                        int row = Convert.ToInt32(parts[1]);    // 排是第二个数字
                        int col = Convert.ToInt32(parts[2]);    // 列是第三个数字
                        int lev = Convert.ToInt32(parts[3]);  // 层是第
                        string modifiedcellcode = $"Cell:{rou}_4_{col}_{lev}_2";
                        var inventorycell = _inventoryRepository.QueryEntityWhere(x => x.LocationCode == modifiedcellcode);
                        if (inventorycell != null && inventorycell.Status == 1)
                        {
                            message = item.Code;
                            return true;
                        }
                        else
                            continue;
                    }
                }
            }
            message = "无可用仓位!";
            return false;
        }

        public List<SubmitOutListDTO> GetCellDepth(List<SubmitOutListDTO> m)
        {
            Dictionary<long, int?> keyValuePairs = new Dictionary<long, int?>();
            foreach (var item in m)
            {
                var depth = _lockCellRepository.QueryEntityById(item.OrderDetId)?.CellDepthIndex;
                if (depth == null)
                {
                    continue;
                }
                else
                {
                    keyValuePairs.Add(item.OrderDetId, depth);
                }
            }
            keyValuePairs = keyValuePairs.OrderBy(x => x.Value).ToDictionary(x => x.Key, x => x.Value);
            var slist = new List<SubmitOutListDTO>();
            foreach (var item in keyValuePairs)
            {
                SubmitOutListDTO submitOutListDTO = new SubmitOutListDTO();
                submitOutListDTO.OrderDetId = item.Key;
                submitOutListDTO.PalletBarcode = m.FirstOrDefault(x => x.OrderDetId == item.Key)?.PalletBarcode;
                submitOutListDTO.Qty = m.FirstOrDefault(x => x.OrderDetId == item.Key)?.Qty ?? 0;
                slist.Add(submitOutListDTO);
            }
            return slist;
        }
        public bool ERPAddShippingOrderDetail(ErpShippingOrderDTO erpShippingOrder, out string message)
        {
            message = string.Empty;
            ShippingOrderDetail shippingOrderDetail = new();
            shippingOrderDetail.OrderSn = erpShippingOrder.BillNo;
            shippingOrderDetail.Status = 0;
            //shippingOrderDetail.BatchNo = erpShippingOrder.BatchNo;
            shippingOrderDetail.ProductCode = erpShippingOrder.ProductCode;
            shippingOrderDetail.ProductName = erpShippingOrder.ProductName;
            shippingOrderDetail.ProductModelSpec = erpShippingOrder.ProductModelSpec;
            shippingOrderDetail.ProductUnitName = erpShippingOrder.ProductUnitName;
            shippingOrderDetail.ProductQty = (int)erpShippingOrder.ProductQty;
            shippingOrderDetail.ProOrderNo = erpShippingOrder.ProOrderNo;
            shippingOrderDetail.DeptCode = erpShippingOrder.WorkShopCode;
            var departmentname = string.Empty;
            if (!string.IsNullOrEmpty(erpShippingOrder.WorkShopCode))
            {
                var department = _departMentRepository.QueryEntityWhere(d => d.DepartmentCode == erpShippingOrder.WorkShopCode);
                departmentname = department.DepartmentName;
            }


            shippingOrderDetail.DeptName = departmentname;
            shippingOrderDetail.OtherTypeCode = erpShippingOrder.OtherTypeCode;
            // shippingOrderDetail.SourceType = erpShippingOrder.BillType;
            //shippingOrderDetail.PurOrderLineType = erpShippingOrder.BillType;
            if (!string.IsNullOrEmpty(erpShippingOrder.Subcontract))
            {
                
                    if (erpShippingOrder.Subcontract.Contains("普通订单"))
                    {
                        shippingOrderDetail.PurOrderLineType = 5;
                        shippingOrderDetail.PurOrderLineNo = "普通订单";
                    }
                    else
                    {
                        shippingOrderDetail.PurOrderLineType = 6;
                        shippingOrderDetail.PurOrderLineNo = "返修订单";
                    }
                
            }
            else
            {
                if (!string.IsNullOrEmpty(erpShippingOrder.OtherTypeCode))
                {

                   var otherType= _otherTypeRepository.QueryEntityWhere(d => d.TypeCode == erpShippingOrder.OtherTypeCode);
                    shippingOrderDetail.PurOrderLineType = null;
                    shippingOrderDetail.PurOrderLineNo = otherType.TypeName;
                    shippingOrderDetail.OtherTypeCode = otherType.TypeCode;
                }
                else
                {
                    if (erpShippingOrder.ProductName == "空托盘")
                    {
                        shippingOrderDetail.PurOrderLineType = 7;
                        shippingOrderDetail.PurOrderLineNo = "空托盘出库";
                    }
                    else
                    {
                        if (erpShippingOrder.TranType!= "生产投料")
                        {
                            shippingOrderDetail.PurOrderLineType = 4;
                            shippingOrderDetail.PurOrderLineNo = "生产报废补料单";

                        }
                        else
                        {
                            shippingOrderDetail.PurOrderLineType = 3;
                            shippingOrderDetail.PurOrderLineNo = "生产投料单";
                        }
                    }
                    
                }
            }
            var suspend = false;
            shippingOrderDetail.CreateDate = DateTime.Now;
            shippingOrderDetail.ModifyDate = DateTime.Now;
            shippingOrderDetail.CreateUserId = 0;
            shippingOrderDetail.ShippedQty = 0;
            shippingOrderDetail.IsDel = false;
            shippingOrderDetail.IsSuspend = suspend;

            try
            {
                _unitOfWork.BeginTransaction();
                foreach (var item in erpShippingOrder.items)
                {

                    var mateial = _materialRepository.QueryEntityWhere(d => d.Code == item.MaterialCode);
                    var warehouseId = mateial.TypeName == "Y"
                                    ? 0666038277042181
                                    : 666038409969669;
                    suspend = mateial.TypeName == "Y" ? true : false;
                    var waresehousecode = _warehouseRepository.QueryIsEntityWhere(d => d.Id == warehouseId)?.Code ?? string.Empty;
                    decimal? OutQtyData = item.Qty;
                    //将物料全部查询出来根据入库时间,库存数量,仓位深度来排序 
                    var inventoryList = _inventoryRepository.GetEntityWhereAll(i => i.Status == 1 && i.IsLock == false && i.WarehouseCode == waresehousecode && i.MaterialCode == item.MaterialCode).OrderBy(i => i.CreateDate.Date).ThenBy(i => i.LocationDepth).ThenByDescending(i => i.AvailableQty).ToList();
                    if(item.InventoryId!=null && item.InventoryId > 0)
                    {
                        inventoryList = inventoryList.Where(d => d.Id == item.InventoryId).ToList();
                    }
                    if (inventoryList.Count() <= 0)
                    {
                        message = "找不到库存信息！" + item.MaterialName;
                        _unitOfWork.RollbackChanges();
                        return false;
                    }
                    //首先判断库存数量是否够出
                    var inventoryMaterialCount = inventoryList.Sum(i => i.AvailableQty);
                    if (inventoryMaterialCount < item.Qty)
                    {
                        message = item.MaterialName + "库存数量不足,目前库存数量为" + inventoryMaterialCount;
                        _unitOfWork.RollbackChanges();
                        return false;
                    }

                    foreach (var inventory in inventoryList)
                    {
                        ShippingLockCell shippingLockCell = new();
                        shippingLockCell.MaterialCode = item.MaterialCode;
                        shippingLockCell.MaterialName = item.MaterialName;
                        shippingLockCell.PartSendDate = item.PartSendDate;
                        shippingLockCell.ModelSpec= item.ModelSpec;
                        shippingLockCell.Status = 0;
                        shippingLockCell.CreateDate = DateTime.Now;
                        shippingLockCell.CreateUserId = 0;
                        shippingLockCell.IsDel = false;
                        shippingLockCell.PartSendDate = item.PartSendDate;
                        if (OutQtyData - inventory.AvailableQty == 0)//如果库存数量等于出库数量则为直出
                        {
                            inventory.PickedQty += inventory.AvailableQty;
                            inventory.IsLock = true;
                            shippingOrderDetail.BillType = 1;
                            shippingLockCell.OutQty = inventory.AvailableQty; //当前库存数量等于出库数量时出库数量为库存数量
                        }
                        if (OutQtyData - inventory.AvailableQty < 0) //如果库存数量大于出库数量则为拣选出库
                        {
                            inventory.PickedQty += OutQtyData;
                            inventory.IsLock = true;
                            shippingOrderDetail.BillType = 2;
                            shippingLockCell.OutQty = OutQtyData; //库存数量大于出库数量时为出库数量为出库数量
                        }
                        if (OutQtyData - inventory.AvailableQty > 0)//当前库存数量小于出库数量则为直出但是需要进行下个库存
                        {

                            inventory.PickedQty += inventory.AvailableQty;
                            inventory.IsLock = true;
                            shippingOrderDetail.BillType = 1;
                            shippingLockCell.OutQty = inventory.AvailableQty; //当前库存数量小于出库数量时出库数量为库存数量
                        }
                        OutQtyData -= inventory.AvailableQty; //减去本次出库库存数量

                        #region 出库单字段和库存字段修改
                        shippingOrderDetail.AreaCode = inventory.AreaCode;
                        shippingOrderDetail.AreaName = inventory.AreaName;
                        shippingOrderDetail.WarehouseId = inventory.WarehouseId;
                        shippingOrderDetail.IsOnceOut = inventory.Capsule == 0 ? false : true;
                        shippingOrderDetail.WarehouseCode = inventory.WarehouseCode;
                        shippingOrderDetail.WarehouseName = inventory.WarehouseName;
                        shippingOrderDetail.MaterialId = inventory.MaterialId == null ? 0 : Convert.ToInt64(inventory.MaterialId);
                        shippingOrderDetail.MaterialName = inventory.MaterialName;
                        shippingOrderDetail.MaterialCode = inventory.MaterialCode;
                        shippingOrderDetail.MaterialTypeCode = inventory.MaterialTypeCode;
                        //shippingOrderDetail.UnitId = inventory.UnitId;
                        shippingOrderDetail.UnitName = item.UnitName; //将明细计量单位赋值给单子
                        shippingOrderDetail.Qty = shippingLockCell.OutQty;
                        shippingOrderDetail.BatchNo = inventory.BatchNo;
                        _shippingOrderDetailRepository.AddEntity(shippingOrderDetail);
                        if (!_unitOfWork.SaveChangesEntity())
                        {
                            message = "添加出库单失败";
                            _unitOfWork.RollbackChanges();
                            return false;
                        }
                        #endregion

                        #region 出库单明细添加
                        shippingLockCell.IsPicking = true;
                        shippingLockCell.OrderDetailId = shippingOrderDetail.Id;
                        shippingLockCell.OrdeSn = shippingOrderDetail.OrderSn;
                        shippingLockCell.InventoryId = inventory.Id;
                        shippingLockCell.CellId = inventory.LocationId;
                        shippingLockCell.CellCode = inventory.LocationCode;
                        shippingLockCell.CellName = inventory.LocationName;
                        shippingLockCell.StockCode = inventory.StockCode;
                        shippingLockCell.StockName = inventory.StockName;
                        shippingLockCell.SupplierName = inventory.SupplierName;
                        shippingLockCell.CellDepthIndex = inventory.LocationDepth;
                        shippingLockCell.WhId = inventory.WarehouseId;
                        shippingLockCell.PalletBarcode = inventory.PalletBarcode;
                        shippingLockCell.MaterialId = inventory.MaterialId;
                        shippingLockCell.MaterialCode = inventory.MaterialCode;
                        shippingLockCell.MaterialName = inventory.MaterialName;
                        
                        shippingLockCell.MaterialKeyId = inventory.MaterialKeyId;
                        shippingLockCell.RoutewayId = inventory.RoutewayId;
                        shippingLockCell.BatchNo = inventory.BatchNo;
                        shippingLockCell.InventoryQty = inventory.AvailableQty;
                        if (shippingLockCell.OutQty == 0)
                        {
                            message = "出库数量不能为0！";
                            _unitOfWork.RollbackChanges();
                            return false;
                        }
                        if (shippingLockCell.OutQty > inventory.AvailableQty)
                        {
                            message = "出库数量不能大于库存可用数量！" + inventory.AvailableQty;
                            _unitOfWork.RollbackChanges();
                            return false;
                        }
                        if (shippingLockCell.OutQty % 1 != 0)
                        {
                            message = "出库数量不能是小数";
                            _unitOfWork.RollbackChanges();
                            return false;
                        }
                        _lockCellRepository.AddEntity(shippingLockCell);
                        _inventoryRepository.UpdEntity(inventory);
                        if (!_unitOfWork.SaveChangesEntity())
                        {
                            message = "添加出库单失败";
                            _unitOfWork.RollbackChanges();
                            return false;
                        }

                        #endregion

                        if (OutQtyData <= 0)
                        {
                            break;
                        }
                    }
                }
                _unitOfWork.CommitChanges();
                return true;
            }
            catch (Exception)
            {
                _unitOfWork.RollbackChanges();
                throw;
            }

        }
       public bool ERPAddSendOrderDetail(ErpSendOrderDTO erpSendOrder, out string message)
        {
            message = string.Empty;
            ShippingOrderDetail shippingOrderDetail = new();
            shippingOrderDetail.OrderSn = erpSendOrder.BillNo;
            shippingOrderDetail.Status = 0;
            shippingOrderDetail.BillDate = erpSendOrder.BillDate;
            shippingOrderDetail.CustomCode = erpSendOrder.CustomCode;
            shippingOrderDetail.CustomerName = erpSendOrder.CustomName;
            shippingOrderDetail.SendAddress = erpSendOrder.SendAddress;
            shippingOrderDetail.SendOrgan=erpSendOrder.SendOrgan;
            shippingOrderDetail.PurOrderLineType = 5;
            shippingOrderDetail.PurOrderLineNo = "调拨单(成品发货部分)";
            var suspend = false;
            shippingOrderDetail.CreateDate = DateTime.Now;
            shippingOrderDetail.ModifyDate = DateTime.Now;
            shippingOrderDetail.CreateUserId = 0;
            shippingOrderDetail.ShippedQty = 0;
            shippingOrderDetail.IsDel = false;
            shippingOrderDetail.IsSuspend = suspend;

            try
            {
                _unitOfWork.BeginTransaction();
                foreach (var item in erpSendOrder.items)
                {

                    var mateial = _materialRepository.QueryEntityWhere(d => d.Code == item.MaterialCode && d.ModelSpec == item.ModelSpec);
                    var warehouseId = mateial.TypeName == "Y"
                                    ? 0666038277042181
                                    : 666038409969669;
                    suspend = mateial.TypeName == "Y" ? true : false;
                    var waresehousecode = _warehouseRepository.QueryIsEntityWhere(d => d.Id == warehouseId)?.Code ?? string.Empty;
                    decimal? OutQtyData = item.Qty;
                    //将物料全部查询出来根据入库时间,库存数量,仓位深度来排序 
                    var inventoryList = _inventoryRepository.GetEntityWhereAll(i => i.Status == 1 && i.IsLock == false  && i.WarehouseCode == waresehousecode && i.MaterialCode == item.MaterialCode).OrderBy(i => i.CreateDate.Date).ThenBy(i => i.LocationDepth).ThenByDescending(i => i.AvailableQty).ToList();
                    if (!string.IsNullOrEmpty(item.SupplierName) )
                    {
                        inventoryList.Where(d => d.SupplierName == item.SupplierName).ToList();
                    }
                    if (!string.IsNullOrEmpty(item.StockCode))
                    {
                        inventoryList.Where(d => d.StockCode == item.StockCode).ToList();
                    }
                    if (!string.IsNullOrEmpty(item.BatchNo))
                    {
                        inventoryList.Where(d => d.BatchNo == item.BatchNo).ToList();
                    }
                    if (inventoryList.Count() <= 0)
                    {
                        message = "找不到库存信息！" + item.MaterialName;
                        _unitOfWork.RollbackChanges();
                        return false;
                    }
                    //首先判断库存数量是否够出
                    var inventoryMaterialCount = inventoryList.Sum(i => i.AvailableQty);
                    if (inventoryMaterialCount < item.Qty)
                    {
                        message = item.MaterialName + "库存数量不足,目前库存数量为" + inventoryMaterialCount;
                        _unitOfWork.RollbackChanges();
                        return false;
                    }

                    foreach (var inventory in inventoryList)
                    {
                        ShippingLockCell shippingLockCell = new();
                        shippingLockCell.MaterialCode = item.MaterialCode;
                        shippingLockCell.MaterialName = item.MaterialName;
                        shippingLockCell.Status = 0;
                        shippingLockCell.CreateDate = DateTime.Now;
                        shippingLockCell.CreateUserId = 0;
                        shippingLockCell.IsDel = false;
                       
                        if (OutQtyData - inventory.AvailableQty == 0)//如果库存数量等于出库数量则为直出
                        {
                            inventory.PickedQty += inventory.AvailableQty;
                            inventory.IsLock = true;
                            shippingOrderDetail.BillType = 1;
                            shippingLockCell.OutQty = inventory.AvailableQty; //当前库存数量等于出库数量时出库数量为库存数量
                        }
                        if (OutQtyData - inventory.AvailableQty < 0) //如果库存数量大于出库数量则为拣选出库
                        {
                            inventory.PickedQty += OutQtyData;
                            inventory.IsLock = true;
                            shippingOrderDetail.BillType = 2;
                            shippingLockCell.OutQty = OutQtyData; //库存数量大于出库数量时为出库数量为出库数量
                        }
                        if (OutQtyData - inventory.AvailableQty > 0)//当前库存数量小于出库数量则为直出但是需要进行下个库存
                        {

                            inventory.PickedQty += inventory.AvailableQty;
                            inventory.IsLock = true;
                            shippingOrderDetail.BillType = 1;
                            shippingLockCell.OutQty = inventory.AvailableQty; //当前库存数量小于出库数量时出库数量为库存数量
                        }
                        OutQtyData -= inventory.AvailableQty; //减去本次出库库存数量

                        #region 出库单字段和库存字段修改
                        shippingOrderDetail.AreaCode = inventory.AreaCode;
                        shippingOrderDetail.AreaName = inventory.AreaName;
                        shippingOrderDetail.WarehouseId = inventory.WarehouseId;
                        shippingOrderDetail.IsOnceOut = inventory.Capsule == 0 ? false:true ;
                        shippingOrderDetail.WarehouseCode = inventory.WarehouseCode;
                        shippingOrderDetail.WarehouseName = inventory.WarehouseName;
                        shippingOrderDetail.MaterialId = inventory.MaterialId == null ? 0 : Convert.ToInt64(inventory.MaterialId);
                        shippingOrderDetail.MaterialName = inventory.MaterialName;
                        shippingOrderDetail.MaterialCode = inventory.MaterialCode;
                        shippingOrderDetail.MaterialTypeCode = inventory.MaterialTypeCode;
                        //shippingOrderDetail.UnitId = inventory.UnitId;
                        shippingOrderDetail.UnitName = item.UnitName; //将明细计量单位赋值给单子
                        shippingOrderDetail.Qty = shippingLockCell.OutQty;
                        shippingOrderDetail.BatchNo = inventory.BatchNo;
                        _shippingOrderDetailRepository.AddEntity(shippingOrderDetail);
                        if (!_unitOfWork.SaveChangesEntity())
                        {
                            message = "添加出库单失败";
                            _unitOfWork.RollbackChanges();
                            return false;
                        }
                        #endregion

                        #region 出库单明细添加
                        shippingLockCell.IsPicking = true;
                        shippingLockCell.OrderDetailId = shippingOrderDetail.Id;
                        shippingLockCell.OrdeSn = shippingOrderDetail.OrderSn;
                        shippingLockCell.InventoryId = inventory.Id;
                        shippingLockCell.CellId = inventory.LocationId;
                        shippingLockCell.CellCode = inventory.LocationCode;
                        shippingLockCell.CellName = inventory.LocationName;
                        shippingLockCell.CellDepthIndex = inventory.LocationDepth;
                        shippingLockCell.WhId = inventory.WarehouseId;
                        
                        shippingLockCell.PalletBarcode = inventory.PalletBarcode;
                        shippingLockCell.MaterialId = inventory.MaterialId;
                        shippingLockCell.MaterialCode = inventory.MaterialCode;
                        shippingLockCell.MaterialName = inventory.MaterialName;
                        shippingLockCell.MaterialKeyId = inventory.MaterialKeyId;
                        shippingLockCell.RoutewayId = inventory.RoutewayId;
                        shippingLockCell.BatchNo = inventory.BatchNo;
                        shippingLockCell.InventoryQty = inventory.AvailableQty;
                        if (shippingLockCell.OutQty == 0)
                        {
                            message = "出库数量不能为0！";
                            _unitOfWork.RollbackChanges();
                            return false;
                        }
                        if (shippingLockCell.OutQty > inventory.AvailableQty)
                        {
                            message = "出库数量不能大于库存可用数量！" + inventory.AvailableQty;
                            _unitOfWork.RollbackChanges();
                            return false;
                        }
                        if (shippingLockCell.OutQty % 1 != 0)
                        {
                            message = "出库数量不能是小数";
                            _unitOfWork.RollbackChanges();
                            return false;
                        }
                        _lockCellRepository.AddEntity(shippingLockCell);
                        _inventoryRepository.UpdEntity(inventory);
                        if (!_unitOfWork.SaveChangesEntity())
                        {
                            message = "添加出库单失败";
                            _unitOfWork.RollbackChanges();
                            return false;
                        }

                        #endregion

                        if (OutQtyData <= 0)
                        {
                            break;
                        }
                    }
                }
                _unitOfWork.CommitChanges();
                return true;
            }
            catch (Exception)
            {
                _unitOfWork.RollbackChanges();
                throw;
            }
        }

    }

}
